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

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

报告相同问题?

悬赏问题

  • ¥20 全书网Java爬取数据
  • ¥15 SAP HANA SQL Script 。SUM OVER 怎么加where
  • ¥15 怎么获取红包封面的原始链接,并且获取红包封面序列号
  • ¥100 微信小程序跑脚本授权的问题
  • ¥60 为什么使用python对地震数据进行umap降维后,数据成图会出现不连续的现象
  • ¥100 房产抖音小程序苹果搜不到安卓可以付费悬赏
  • ¥15 STM32串口接收问题
  • ¥15 腾讯IOA系统怎么在文件夹里修改办公网络的连接
  • ¥15 filenotfounderror:文件是存在的,权限也给了,但还一直报错
  • ¥15 MATLAB和mosek的求解问题