简体   繁体   中英

Creating an image with PHP - Large file size

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;
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM