Images can greatly enhance the visual appeal of a website, but they can also slow down page load times if they are not properly optimized. One way to optimize images is by compressing them to reduce their file size without sacrificing quality. In this tutorial, we will be discussing how to compress images using PHP.

Step 1: First, you need to have the GD library installed on your server. The GD library is a powerful image manipulation library for PHP that can be used for a variety of image-related tasks, including compression.

Step 2: Next, you will need to create a new PHP file and name it “compress-images.php”.

Step 3: In this file, you will need to include the following code:

  // Path to the image
  $image_path = 'path/to/image.jpg';

  // Get the original image information
  $original_info = getimagesize($image_path);
  $original_width = $original_info[0];
  $original_height = $original_info[1];

  // Create a new image with a quality of 60
  $image = imagecreatefromjpeg($image_path);
  imagejpeg($image, $image_path, 60);
  // Get the new image information
  $compressed_info = getimagesize($image_path);
  $compressed_width = $compressed_info[0];
  $compressed_height = $compressed_info[1];
  // Calculate the compression rate
  $compression_rate = round((($original_width * $original_height) - ($compressed_width * $compressed_height)) / ($original_width * $original_height), 2) * 100;
  echo "Original Image: {$original_width}x{$original_height}<br>";
  echo "Compressed Image: {$compressed_width}x{$compressed_height}<br>";
  echo "Compression Rate: {$compression_rate}%";


This code uses the GD library’s imagecreatefromjpeg() function to create a new image from the original image file, and then uses the imagejpeg() function to save the new image with a quality of 60. The getimagesize() function is used to get the original and compressed image information and the compression rate is calculated with a simple formula. The final step is to echo out the original image, compressed image and the compression rate.

Note that you can use this method for other image formats like PNG, Gif etc. by replacing imagecreatefromjpeg with imagecreatefrompng, imagecreatefromgif etc.

You can adjust the quality level to your preference, but keep in mind that a lower quality level will result in a smaller file size but also a lower image quality.

By compressing images before uploading them to your website, you can significantly improve page load times and provide a better user experience. I hope this tutorial helps you in optimizing your images for the web using PHP. Happy coding!”