PHP:根据PNG大小从PNG源函数生成PNG缩略图
我编写了这个小函数来生成较大jpg/jpeg/png源代码的缩略图,它在jpg/jpeg图像上工作得非常好,但是根据png图像的大小,它会在不确定的点上崩溃。小型300x200图像可以工作,但类似2880x1800的图像无法工作 以下是我的(带注释的)函数:PHP:根据PNG大小从PNG源函数生成PNG缩略图,php,image,png,thumbnails,Php,Image,Png,Thumbnails,我编写了这个小函数来生成较大jpg/jpeg/png源代码的缩略图,它在jpg/jpeg图像上工作得非常好,但是根据png图像的大小,它会在不确定的点上崩溃。小型300x200图像可以工作,但类似2880x1800的图像无法工作 以下是我的(带注释的)函数: function make_thumb($filename, $destination, $desired_width) { $extension = pathinfo($filename, PATHINFO_EXTENSION);
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';
}
}
我发现的唯一提到类似问题的文档是。这是我的问题吗?有什么解决办法吗?它为什么会这样做?您很可能内存不足。2880 x 1800的真彩色将需要大约20兆字节
检查你的php.ini是否有
内存限制我是个白痴。这或PHP在处理大型PNG图像方面非常糟糕。imagepng()
的PHP文档中有这样一条注释:
我的脚本无法完成:致命错误:允许的内存大小XX字节已用尽(尝试分配XX+n字节)
我发现PHP以未压缩格式处理图像:我的输入图像是8768x4282@32位=>~150 MB每个内存中副本
作为解决方案,您可以检查尺寸并拒绝任何太大的内容,或者像我所做的那样,使用ini_集(“内存限制”,“1024M”);在页面开始处(如果您的服务器有足够的板上内存)
因此,请记住使用ini_set('memory_limit','1024M')增加可用内存限制代码>