Reduce JPEG Filesize "On the Fly" with PHP

Last updated 1 month ago | 51 views 75     5

Tags:- PHP

Reducing the file size of JPEG images dynamically is essential for improving website performance and saving bandwidth. Here's a step-by-step guide to help you achieve this using PHP.

✅ Step 1: Upload the Image

Ensure that the image you want to compress is accessible via your PHP script. For example, you can use a file upload form or specify the file path directly.

✅ Step 2: Load the Image

Use the imagecreatefromjpeg() function to load the JPEG image into PHP.

$image = imagecreatefromjpeg('path/to/your/image.jpg');

✅ Step 3: Set the Compression Level

The imagejpeg() function allows you to specify the compression quality. The quality parameter ranges from 0 (worst quality, smallest file) to 100 (best quality, largest file).

$outputPath = 'path/to/compressed-image.jpg';
$quality = 75; // Adjust this value as needed
imagejpeg($image, $outputPath, $quality);

✅ Step 4: Free Up Memory

After compression, it's essential to free up memory by destroying the image resource.

imagedestroy($image);

✅ Step 5: Handle Output Directly (Optional)

If you want to output the image directly to the browser, you can set the appropriate header and skip saving to a file.

header('Content-Type: image/jpeg');
imagejpeg($image, null, $quality);
imagedestroy($image);

✅ Step 6: Automate Compression for Multiple Images

You can create a loop to compress multiple images in a directory.

$images = glob('images/*.jpg');

foreach ($images as $img) {
    $image = imagecreatefromjpeg($img);
    $output = 'compressed/' . basename($img);
    imagejpeg($image, $output, 75);
    imagedestroy($image);
}

Conclusion

By leveraging PHP’s GD library functions, you can effectively reduce JPEG file sizes on the fly, optimizing your website’s performance and saving bandwidth. Adjust the compression level to find the right balance between quality and size.