I was using the firebug page speed utility and one of the suggestions given was to compress the images - So I wrote the following code to compress the image
$filename="http://localhost.com/snapshots/picture.png"; $img = imagecreatefrompng($filename); $this->_response->setHeader('Content-Type', 'image/png'); imagepng($img,null,9); imagedestroy($img);
Now the actual image size is 154K So I experimented by giving different quality levels and here is what I found
imagepng($img,null,0); --> Size = 225K imagepng($img,null,1); --> Size = 85.9K imagepng($img,null,2); --> Size = 83.7K imagepng($img,null,3); --> Size = 80.9K imagepng($img,null,4); --> Size = 74.6K imagepng($img,null,5); --> Size = 73.8K imagepng($img,null,6); --> Size = 73K imagepng($img,null,7); --> Size = 72.4K imagepng($img,null,8); --> Size = 71K imagepng($img,null,9); --> Size = 70.6K
Do these results look accurate - I'm not sure why with quality 0 - the image size is larger than the actual size.
Secondly is this the best way to go about in PHP to compress images before rendering them in the browser to improve performance.
Based on the suggestions, that its better to compress the image once at the time of saving - I digged up the code that is called by the flash program to generate the snap shot -
$video = $this->_getParam('video'); $imgContent = base64_decode($this->_getParam('snapshot')); file_put_contents("snapshots/" . $video . ".png", $imgContent);
EDITED Based on Alvaro's suggestion, I have made the following modification to the code which generates a much small jpg file
$video = $this->_getParam('video'); $imgContent = base64_decode($this->_getParam('snapshot')); file_put_contents("snapshots/" . $video . ".png", $imgContent); $filename="snapshots/".$video.".png"; $img = imagecreatefrompng($filename); imagejpeg($img,'test.jpg',75);
So now this is a 3 step process
- create the initial image using file_put_contents
- Use imagecreatefrompng and imagejpeg to compress the file and generate a smaller image
- Delete the orig image
Is this the best optimal way to go about it.