How to compress images in php using gd

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 are few examples

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.







Last Updated On : 12th March 2013

Subscribe to get updates delivered to your inbox

1 Comment + Add Comment

Leave a comment