How to compress images in Php using GD Library

By | May 2, 2023

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.

About Silver Moon

A Tech Enthusiast, Blogger, Linux Fan and a Software Developer. Writes about Computer hardware, Linux and Open Source software and coding in Python, Php and Javascript. He can be reached at [email protected].

3 Comments

How to compress images in Php using GD Library

Leave a Reply

Your email address will not be published. Required fields are marked *