我编写了这个小函数来生成较大 jpg/jpeg/png 源的缩略图图像,它在 jpg/jpeg 图像上完美运行,但根据 png 图像的大小,该函数会在不确定的点崩溃。300x200 的小图像可以工作,但 2880x1800 之类的图像则不行。
这是我的(带注释的)函数:
function make_thumb($filename, $destination, $desired_width) {
$extension = pathinfo($filename, PATHINFO_EXTENSION);
// Read source image
if ($extension == 'jpg' || $extension == 'jpeg') {
$source_image = imagecreatefromjpeg($filename);
} else if ($extension == 'png') {
$source_image = imagecreatefrompng($filename); // I think the crash occurs here.
} else {
return 'error';
}
$width = imagesx($source_image);
$height = imagesy($source_image);
$img_ratio = floor($height / $width);
// Find the "desired height" of this thumbnail, relative to the desired width
$desired_height = floor($height * ($desired_width / $width));
// Create a new "virtual" image
$virtual_image = imagecreatetruecolor($desired_width, $desired_height);
// Copy source image at a resized size
imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height);
// Create the physical thumbnail image to its destination
if ($extension == 'jpg' || $extension == 'jpeg') {
$source_image = imagejpeg($virtual_image, $destination);
} else if ($extension == 'png') {
$source_image = imagepng($virtual_image, $destination, 1);
} else {
return 'another error';
}
}
我发现的唯一与我提到类似问题的文档是this。这是我的问题吗?有什么解决办法吗?为什么这样做?