Hello, please sign in or register
You are here: Home

PNG Optimization with GD library

PNG (Portable Network Graphics) optimization is not always easy to manage.

First off PNG is not one format but five different formats (see table)
  Bit depth per channel
16
Number
of
channels
indexed 1 1 2 4 8
greyscale 1 1 2 4 8 16
greyscale & alpha 2


16 32
truecolor 3


24 48
truecolor & alpha 4


32 64
  Bits per pixel


So there are 5 different types of PNG's, each with their own tradeoff between colour, alpha (transparency) and number of bits per pixel (i.e. filesize of picture)

Dont Optimize all PNG's in the same way

I've used GD library to resize many PNG's as they are required but writing a generic function to resize any of these, without treating them differently, can either lose information (e.g. transparency) or create a file unnecessarily large. Additionally a PNG file were sometimes not optimized themselves. A PNG could be saved as PNG32 (truecolor+alpha) and have just 10 colors and be better off saved as an indexed palette.


The Code

Below is some code which i've used to check what the image is. I'm assuming that you know roughly how to use the GD functions.

This is effectively the logic
  1. Is this a palette image with an Alpha Transparency?
    e.g. imagecolortransparent($i)>=0 || (ord(file_get_contents ($img, false, null, 25, 1)) & 4)
  2. Process as having an Alpha channel, but if this still has a palette we might reduce the file to use PNG8.
    e.g. if(($tc=imagecolorstotal($i))&&$tc<=256)
                           imagetruecolortopalette($d, false, $tc)
  3. Resize image
    e.g. imagecopyresampled($d, $i, 0, 0, 0, 0, $w, $h, $s[0], $s[1]);
  4. Does the PNG format support Alpha transparency
    e.g. (ord(file_get_contents ($img, false, null, 25, 1)) & 4) 
  5. Take a collection of the new image pixels and find evidence of transparency
    e.g. imagecolorsforindex($d, imagecolorat($d,$x,$y))
    Otherwise mark as palette
  6. If this is a palette image without transparency then, reduce to an indexed file.
    e.g.  imagetruecolortopalette($d, false, 256);

Code basics
<?php
/**
* Image PNG
* Take a PNG image and create a thumbnail, maintaining alpha transparency for a png-24 image.
*/

$m = microtime(true);

$img = "someimage.png";

// Size
$s = getimagesize( $img );

// Resize dimensions
$w = 400;
$h = round($w*($s[1]/$s[0]));

// Source
$i = imagecreatefrompng( $img );
// Destination
$d = imagecreatetruecolor($w,$h);

// if this has no alpha transparency defined as an index
// it could be a palette image??
$palette = (imagecolortransparent($i)<0);

// If this has transparency, or is defined
if(!$palette||(ord(file_get_contents ($img, false, null, 25, 1)) & 4)){
print ("Is Alpha");
// Has indexed transparent color
if(($tc=imagecolorstotal($i))&&$tc<=256)
imagetruecolortopalette($d, false, $tc);
imagealphablending($d, false);
$alpha = imagecolorallocatealpha($d, 0, 0, 0, 127);
imagefill($d, 0, 0, $alpha);
imagesavealpha($d, true);
var_dump(microtime(true)-$m);
}

// Resample Image
print ("Resampling Image");
imagecopyresampled($d, $i, 0, 0, 0, 0, $w, $h, $s[0], $s[1]);
var_dump(microtime(true)-$m);

// Did the original PNG supported Alpha?
if((ord(file_get_contents ($img, false, null, 25, 1)) & 4)){
print ("Testing is there is Alpha transparency");

// we dont have to check every pixel.
// We take a sample of 2500 pixels (for images between 50X50 up to 500X500), then 1/100 pixels thereafter.
$dx = min(max(floor($w/50),1),10);
$dy = min(max(floor($h/50),1),10);

$palette = true;
for($x=0;$x<$w;$x=$x+$dx){
for($y=0;$y<$h;$y=$y+$dy){
$col = imagecolorsforindex($d, imagecolorat($d,$x,$y));
// How transparent until it's actually visible
// I reackon atleast 10% of 127 before its noticeable, e.g. ~13
if($col['alpha']>13){
//print_r($col);
$palette = false;
break 2;
}
}
}
var_dump(microtime(true)-$m);
var_dump( !$palette );
}

if($palette){
print "Converting to indexed colors";
imagetruecolortopalette($d, false, 256);
var_dump(microtime(true)-$m);
}

// Save file, quality=9, Add filters... although sometimes better without.
imagepng( $d, 'newpath.png', 9, PNG_ALL_FILTERS);

?>

Please note: I've tested this on small number of PNG's with great success, but you might like to tune the settings before images are irreversibly replaced.... or back them up.


References

Get more information at php.net/image and read the comments which others had left, i have taken a few ideas from them to create this article but its 90% my own work.

Additionally there are some other tools to reduce PNG files.
  • The excellent "Save for Web" in Adobe Photoshop is very good and because you can see the quality you'll get better results... but its a labour intensive solution
  • PNGcrush is a linux command, albeit more of a loss-less compression tool.

Comments

Question on Transparency
Hi there, thank you for your post here great information. If you have time, and you know this answer, I would so appreciate a quick note on how to resolve. I am tasked with coloring of product (eg. t-shirt) where they may be layers that are colored...
Created 10/05/11
LMrjIZpwbPEZzymi
If you're raiedng this, you're all set, pardner!
Created 18/08/11
XKXSpxMSoCEfq
sCttZ6 fglmyvnkawqa
Created 19/08/11
HzWXChUdJV
9w5G75 , [url=http://ytudovyhjeep.com/]ytudovyhjeep[/url], [link=http://hhoxrgaqybsm.com/]hhoxrgaqybsm[/link], http://ofopfoxerrnh.com/
Created 20/08/11
PwocCWQlPepFAX
xNkprc vxydsfbmkinj
Created 25/08/11
QLmygYZbpScSrV
BNBJB1 , [url=http://jspnemskcwpi.com/]jspnemskcwpi[/url], [link=http://sjwxpumtipyx.com/]sjwxpumtipyx[/link], http://ktxueywrbggp.com/
Created 30/08/11
Nice
Nice script
Created 04/07/12
cmoutlet
s ralph lauren outlet Ray Ban Sunglasses,Ray Ban Outlet,Ray Ban Sale,Cheap Ray Bans,Cheap Ray Ban Sunglasses,ray ban sunglasses outlet,ray ban,rayb...
Created 21/10/15
oakleysunglasses
“I canada goose outlet think it doesn’t swarovski jewelry bode very
Created 21/01/16
linpingping
The michael--kors.org.uk next ralph lauren outlet day patriots jersey Mrs
Created 01/03/16
clibin
Tyrion 5c cases watched her ray ban sunglasses read. His timber...
Created 18/04/16
chenyan
Bond grinned. pandora-bracciali.it "We bcbgmax.in.net only chaussure...
Created 15/06/16
chenyan
Bond grinned. pandora-bracciali.it "We bcbgmax.in.net only chaussure...
Created 15/06/16
chenyan
Bond grinned. pandora-bracciali.it "We bcbgmax.in.net only chaussure...
Created 15/06/16
chenyan
Bond grinned. pandora-bracciali.it "We bcbgmax.in.net only chaussure...
Created 15/06/16
wq123
p90x3, ray ban pas cher, longchamp, uggs on sale,
Created 30/06/16
wq123
p90x3, ray ban pas cher, longchamp, uggs on sale,
Created 30/06/16
ninestab123
ninest123 One canada goose pas cher gucci outlet thing
Created 21/07/16
ZZZZ
michael kors handbags nike trainers
Created 05/10/16
Title*
Comment

Prove you are not a robot

To prove you are not a robot, please type in the six character code you see in the picture below
Security confirmation codeI can't see this!
Contact
Name*
Email never shown*
Home Page

Author

Andrew Dodson
Since:Feb 2007

Comment | flag

Categories

Bookmark and Share