douqiangchuai7674 2012-12-23 20:07
浏览 31
已采纳

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

The Problem

I'm trying to resize a 260x310px PNG to 120x120px while also retaining the transparency and centring the image. I have included the function i'm using below, it works fine in terms of the appearance of the image, however the images created are alot bigger. Infact all the images appear to be 128kb (there are thousands I haven't looked at all of them) and a directory of 50,000 of these images is 1gb bigger despite the images being over half the size (in pixels).

I imagine this is because PHP isn't doing any optimisation in the way that say Photoshop might. Is there anything I can do to optimise the image in PHP?

The Code

This is my Code:

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;
}
  • 写回答

1条回答 默认 最新

  • duangou1868 2012-12-23 20:09
    关注

    While it might be possible to optimize the file with PHP, it will be easiest to run it through a program like pngcrush.

    With GD you could try using the third parameter of imagepng "quality" and set it to 9 (you have it set to 0 = no compression) but you will gain much more with a specialized PNG optimizer.

    Also check this question: PNG optimisation tools

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建