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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵