Php applications might need to do some image processing if they are allowing users to upload pictures of somekind. This can include cropping, watermarking, compressing etc.
To compress an image the quality needs to be adjusted.
Here is a code example of how to do it:
function compress_image($src, $dest , $quality) { $info = getimagesize($src); if ($info['mime'] == 'image/jpeg') { $image = imagecreatefromjpeg($src); } elseif ($info['mime'] == 'image/gif') { $image = imagecreatefromgif($src); } elseif ($info['mime'] == 'image/png') { $image = imagecreatefrompng($src); } else { die('Unknown image file format'); } //compress and save file to jpg imagejpeg($image, $dest, $quality); //return destination file return $dest; } //usage $compressed = compress_image('boy.jpg', 'destination.jpg', 50);
The above function will process a jpg/gif/png image and compress it and save to jpg format. The actual compression takes place in just oneline, that is the imagejpeg function. The quality value controls the amount of compression that is applied.
Lower the quality higher the compression. It should be kept in mind that compression is not lossless and will result in degradation of the image quality.
The above example creates a jpg image from the source. Alternatively the resulting image can be stored as png if transparency needs to be preserved. The function looks like this
imagepng($image, 'destination.png', 5);
The third parameter is the compression value whose value can be between 0-9. Higher value means higher compression and lower size. However png files are much larger in size compared to jpg images.
How does one preserve PNGopacity when using this script?
Nice tutorial but lengthy code there is an simple and short tutorial of how to reduce the image size on TalkersCode.com http://talkerscode.com/webtricks/reduce%20the%20size%20and%20make%20thumbnail%20of%20any%20image%20before%20uploading%20using%20PHP.php
hi lilly the link is not opened