gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-28 23:59:17 26 4
gpt4 key购买 nike

我正在使用这个类:

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, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

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

}

效果很好,但使用 png 失败,它会创建一个调整大小的黑色图像。

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

最佳答案

function resize($newWidth, $targetFile, $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, $newHeight);
imagecopyresampled($tmp, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

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

关于php - 使用 PHP 调整图像大小,支持 PNG、JPG,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13596794/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com