PHP压缩裁剪图片实例

/**
 * @param $srcImage 原图片路径
 * @param $toFile   裁剪后图片路径
 * @param int $maxWidth   裁剪最大的宽度
 * @param int $maxHeight  裁剪后最大的高度
 * @param int $imgQuality 图片的质量
 * @return bool|string|void
 */
function resize($srcImage,$toFile,$maxWidth = 640,$maxHeight = 480,$imgQuality=100)
{
    list($width, $height, $type, $attr) = getimagesize($srcImage);
    if($width < $maxWidth  || $height < $maxHeight) return ;
    switch ($type) {//判断图片类别
        case 1: $img = imagecreatefromgif($srcImage); break;
        case 2: $img = imagecreatefromjpeg($srcImage); break;
        case 3: $img = imagecreatefrompng($srcImage); break;
    }
    $scale = min($maxWidth/$width, $maxHeight/$height);
    if($scale < 1) {
        $newWidth = floor($scale*$width);
        $newHeight = floor($scale*$height);
        $newImg = imagecreatetruecolor($newWidth, $newHeight);
        imagecopyresampled($newImg, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
        $newName = "";
        $toFile = preg_replace("/(.gif|.jpg|.jpeg|.png)/i","",$toFile);
        switch($type) {
            case 1: if(imagegif($newImg, "$toFile$newName.gif", $imgQuality))
                return "$newName.gif"; break;
            case 2: if(imagejpeg($newImg, "$toFile$newName.jpg", $imgQuality))
                return "$newName.jpg"; break;
            case 3: if(imagepng($newImg, "$toFile$newName.png", $imgQuality))
                return "$newName.png"; break;
            default: if(imagejpeg($newImg, "$toFile$newName.jpg", $imgQuality))
                return "$newName.jpg"; break;
        }
        imagedestroy($newImg);
    }
    imagedestroy($img);
    return false;
}

来自微信公众号:编程社

程序员日常进阶宝典,欢迎关注!

posted on 2019-09-02 22:23  黑夜开发者  阅读(355)  评论(0编辑  收藏  举报