Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用PHP创建图像-大文件大小 问题_Php_Image Processing_Png_Image Resizing_Imagecreatefrompng - Fatal编程技术网

使用PHP创建图像-大文件大小 问题

使用PHP创建图像-大文件大小 问题,php,image-processing,png,image-resizing,imagecreatefrompng,Php,Image Processing,Png,Image Resizing,Imagecreatefrompng,我正在尝试将260x310px PNG的大小调整为120x120px,同时保持透明度并使图像居中。我已经包括了我在下面使用的功能,它在图像外观方面工作得很好,但是创建的图像要大得多。事实上,所有的图像看起来都是128kb(有数千个我没有全部看过),其中50000个图像的目录更大1gb,尽管图像的大小(像素)超过一半 我想这是因为PHP没有像Photoshop那样进行任何优化。我可以做些什么来优化PHP中的图像吗 代码 这是我的代码: if ($handle = opendir($mydir_pa

我正在尝试将260x310px PNG的大小调整为120x120px,同时保持透明度并使图像居中。我已经包括了我在下面使用的功能,它在图像外观方面工作得很好,但是创建的图像要大得多。事实上,所有的图像看起来都是128kb(有数千个我没有全部看过),其中50000个图像的目录更大1gb,尽管图像的大小(像素)超过一半

我想这是因为PHP没有像Photoshop那样进行任何优化。我可以做些什么来优化PHP中的图像吗

代码 这是我的代码:

if ($handle = opendir($mydir_path)) {
    while (false !== ($entry = readdir($handle))) {
        if(strpos($entry, '.png'))
        {
            resize($mydir_path.$entry);
        }
    }
    closedir($handle);
}

function resize($img_loc)
{
    $mini_loc = str_replace('megapack', 'handheld_megapack', $img_loc);

    $canvas = imagecreatetruecolor(310, 310);
    imagefill($canvas, 0, 0, imagecolorallocatealpha($canvas, 255, 255, 255, 127));
    imagealphablending($canvas, false);
    imagesavealpha($canvas, true);

    $img = imagecreatefrompng($img_loc);
    imagecopy($canvas, $img, 25, 0, 0, 0, 260, 310);

    $resizedImg = imagecreatetruecolor('120', '120');
    imagefill($resizedImg, 0, 0, imagecolorallocatealpha($resizedImg, 255, 255, 255, 127));
    imagealphablending($resizedImg, false);
    imagesavealpha($resizedImg, true);

    imagecopyresampled($resizedImg, $canvas, 0, 0, 0, 0, '120', '120', '310', '310');

    $dirname = dirname($mini_loc);

    imagepng($resizedImg, $mini_loc, '0');

    chmod($mini_loc, 0666);

    return $mini_loc;
}

虽然可以使用PHP优化该文件,但通过类似的程序运行它将是最简单的

使用GD,您可以尝试使用第三个参数“quality”,并将其设置为9(您将其设置为0=无压缩),但使用专门的PNG优化器,您将获得更多


同时检查这个问题:

我一直在看pngcrush,它可能是解决方案。我会给你一个+1,但希望有人能对优化PHP生成的图像给出一些见解:)谢谢,我已经扩展了我的答案。啊,该死,这看起来太明显了!这大大减少了文件大小,仅为20kb,并且没有明显的质量损失。此外,在9优化小于1kb的图像上使用pngcrush后,随后保存了9优化,因此9优化似乎足够了。在没有明显的质量损失的情况下,我们制作了3gb dir 1gb。答案太明显了,我有点尴尬!