A Simple Example to Compress Images in PHP – PHP Examples

By | April 17, 2019

Compressing images is often used in web application, in this tutorial, we will write a php example for you to compress an image.

How to compress image in php?

Step 1. Copy and paste php code below into a php file

<?php
function compress($source, $destination, $quality) {
	$info = getimagesize($source);
	if ($info['mime'] == 'image/jpeg') 
		$image = imagecreatefromjpeg($source);
	elseif ($info['mime'] == 'image/gif') 
		$image = imagecreatefromgif($source);
	elseif ($info['mime'] == 'image/png') 
		$image = imagecreatefrompng($source);
	imagejpeg($image, $destination, $quality);
	return $destination;
}
$src = '1.png';
$dest = '2.png';
compress($src, $dest, $quality=50);
?>

Step 2. Prepare two images

These two images are 1.png and 2.png

Step 3. Run this php file

The result is:

Category: PHP

Leave a Reply

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