In modern web development, optimizing image size is crucial for improving page load speed and user experience. Proportional compression allows you to reduce image file size effectively while maintaining the original aspect ratio. This article introduces how to achieve this using PHP's GD library and provides practical code examples.
The basic idea behind proportional image compression is to calculate the target height (or width) based on a given target width (or height) while preserving the original image's aspect ratio. PHP's GD extension facilitates reading image information, creating canvas, resizing, and outputting images with ease.
The first step is to retrieve the original image width and height using the getimagesize() function:
$originalImagePath = 'path/to/original/image.jpg';
$originalImageSize = getimagesize($originalImagePath);
$originalWidth = $originalImageSize[0];
$originalHeight = $originalImageSize[1];
Based on a set target width, calculate the target height proportionally:
$targetWidth = 800;
$targetHeight = $originalHeight * ($targetWidth / $originalWidth);
Use the GD library to create image resources and perform proportional compression:
$originalImage = imagecreatefromjpeg($originalImagePath);
$targetImage = imagecreatetruecolor($targetWidth, $targetHeight);
Then, resize the image using imagecopyresampled():
imagecopyresampled(
$targetImage,
$originalImage,
0, 0, 0, 0,
$targetWidth, $targetHeight,
$originalWidth, $originalHeight
);
Finally, save the compressed image to a specified path:
$targetImagePath = 'path/to/target/image.jpg';
imagejpeg($targetImage, $targetImagePath, 80); // Compression quality set to 80%
With the steps demonstrated here, developers can easily implement proportional image compression in PHP, balancing image quality and file size reduction. This technique is especially useful for optimizing frontend performance in scenarios such as image galleries, article thumbnails, and product images. Mastering this approach helps enhance overall website performance.