使用PHP调整图像大小,支持PNG,JPG

前端之家收集整理的这篇文章主要介绍了使用PHP调整图像大小,支持PNG,JPG前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用这个类:
class ImgResizer {

function ImgResizer($originalFile = '$newName') {
    $this -> originalFile = $originalFile;
}
function resize($newWidth,$targetFile) {
    if (empty($newWidth) || empty($targetFile)) {
        return false;
    }
    $src = imagecreatefromjpeg($this -> originalFile);
    list($width,$height) = getimagesize($this -> originalFile);
    $newHeight = ($height / $width) * $newWidth;
    $tmp = imagecreatetruecolor($newWidth,$newHeight);
    imagecopyresampled($tmp,$src,$newWidth,$newHeight,$width,$height);

    if (file_exists($targetFile)) {
        unlink($targetFile);
    }
    imagejpeg($tmp,$targetFile,95);
}

}

哪个工作出色,但是用png失败,它创建一个调整大小的黑色图像.

有没有办法调整这个类来支持png图像?

function resize($newWidth,$originalFile) {

    $info = getimagesize($originalFile);
    $mime = $info['mime'];

    switch ($mime) {
            case 'image/jpeg':
                    $image_create_func = 'imagecreatefromjpeg';
                    $image_save_func = 'imagejpeg';
                    $new_image_ext = 'jpg';
                    break;

            case 'image/png':
                    $image_create_func = 'imagecreatefrompng';
                    $image_save_func = 'imagepng';
                    $new_image_ext = 'png';
                    break;

            case 'image/gif':
                    $image_create_func = 'imagecreatefromgif';
                    $image_save_func = 'imagegif';
                    $new_image_ext = 'gif';
                    break;

            default: 
                    throw new Exception('Unknown image type.');
    }

    $img = $image_create_func($originalFile);
    list($width,$height) = getimagesize($originalFile);

    $newHeight = ($height / $width) * $newWidth;
    $tmp = imagecreatetruecolor($newWidth,$img,$height);

    if (file_exists($targetFile)) {
            unlink($targetFile);
    }
    $image_save_func($tmp,"$targetFile.$new_image_ext");
}

猜你在找的PHP相关文章