PHP Code for Image Compression
<?php
function compressImage($source, $destination, $quality) {
// Get image info
$imgInfo = getimagesize($source);
$mime = $imgInfo['mime'];
// Create a new image from file
switch ($mime) {
case 'image/jpeg':
$image = imagecreatefromjpeg($source);
break;
case 'image/png':
$image = imagecreatefrompng($source);
break;
case 'image/gif':
$image = imagecreatefromgif($source);
break;
default:
return false;
}
// Save the image
if ($mime == 'image/png') {
// For PNG, use a compression level between 0 (no compression) and 9 (maximum compression)
imagepng($image, $destination, 9);
} else {
// For JPEG and GIF, use the quality setting (1 to 100, with 100 being highest quality)
imagejpeg($image, $destination, $quality);
}
// Free up memory
imagedestroy($image);
return $destination;
}
// Example usage
$sourceImage = 'input.jpg'; // Source image file path
$destinationImage = 'output.jpg'; // Destination image file path
$quality = 70; // Compression quality (1-100)
$result = compressImage($sourceImage, $destinationImage, $quality);
if ($result) {
echo "Image compressed successfully!";
} else {
echo "Failed to compress image.";
}
?>
Explanation:
1. compressImage($source, $destination, $quality):
This function takes the source image path, the destination path for the compressed image, and the quality for compression (1-100).
Based on the MIME type (image/jpeg, image/png, image/gif), it creates an image resource using the respective PHP image creation functions (imagecreatefromjpeg, imagecreatefrompng, imagecreatefromgif).
For JPEG images, it applies the provided quality.
For PNG images, it uses a compression level of 9 (maximum compression).
Finally, the image is saved to the destination path, and memory is freed up with imagedestroy.
2. Compression Quality:
For JPEG, quality is controlled via a value from 0 to 100 (100 being the highest quality and least compression).
For PNG, compression is from 0 to 9 (9 being the most compressed).
GIF format doesn’t support a quality parameter but can be handled similarly.
Usage:
1. Upload the PHP file to your server.
2. Modify $sourceImage and $destinationImage with the correct file paths.
3. Adjust the $quality value to set the desired compression level.
This code will effectively reduce the image file size without compromising too much on quality.