Sublim.design

PHP script for compressing website images on the fly

Published on April 22, 2024

A web page is mainly text and images. Carefully selected illustrations make reading an article more pleasant and enhance the user experience (UX). They encourage visitors to stay longer and explore more content via the general menu, internal links and CTA buttons (Call-To-Acton). The choice of images also helps build a visual identity and contributes to natural referencing (SEO - Search Engine Optimization) thanks in particular to the use of ALT tags and the use of relevant keywords integrated into file names.

The importance of compressing images to reduce page load times

is essential for optimizing the performance of a website; a lightweight image loads faster and improves page display time. Navigation then becomes smoother and more pleasant for the user. Studies show that websites with fast loading times have better conversion rates; this performance indicator (KPI) expresses the percentage of visitors who carry out an action on a website: filling in a contact form, for example, downloading a document, validating a purchase or subscribing to a newsletter.

Page loading time is also taken into account by Google to assess the health of a website: a technically well-made site will have better SEO.

Introducing the method and putting our image compression script into practice

Our PHP script is self-contained, operating without an API and without any external resources. It creates a compressed image, generated from a source image stored on the server. We use the .htaccess file to direct all images in .jpg format to our script named compress.php.

An index.html page to display images

Simplified to the extreme, our HTML page contains no javascript or technical details. It simply displays a single image in two different ways:

index.html
<html>
 <head>
  <title>Compresser les images à la volée</title>
 </head>
 <body>
  <img src="image.jpg" width="480">
  <img src="image-compressed.jpg" width="480">
 </body>
</html>

Use the .htaccess file to redirect images to our script

Placed at the root of an Apache web server (PHP), the .htaccess (Hypertext Access) file is used to define its general operation. It is commonly used to direct erroneous requests to a personalized error page (page 404), redirect old URLs to new pages (301 redirection) or - in our case - redirect images to a PHP script.

In the 3rd line of our example, we indicate that all JPG images ending with the expression compressed should be redirected to the file compress.php.

.htaccess
RewriteEngine On
RewriteBase /
RewriteRule ^(.*)-compressed.jpg compress.php?name=$1 [L]

PHP script for image compression

Our compress.php file will reduce the size and weight of the images, so as to optimize loading times. The variables $rate (compression rate, in percent) and $new_width (new width) can be adjusted to suit your needs.

compress.php
<?php

 // Définition du format 
 header ("Content-type:image/jpeg");

 // Définition des variables
 $name = $_GET['name']; // Récupère le nom du fichier
 $rate = 60; // Taux de compression
 $new_width = 640; // Nouvelle largeur

 $file = $name.".jpg"; 

 // Récupère la résolution de l'image originale
 list($width, $height) = getimagesize($file);

 // Calcul la résolution de l'image compressée
 $ratio = $width/$height;
 $new_height = round($new_width/$ratio);

 // Création et affichage de l'image compressée
 $new_file = imagecreatetruecolor($new_width, $new_height);
 $mask = imagecreatefromjpeg($file);
 imagecopyresampled($new_file, $mask, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
 imagejpeg($new_file,NULL,$rate);
 imagedestroy($new_file);

?>

With this PHP script, you can easily generate compressed images on the fly. Your website will be faster, more responsive and more efficient. You're free to download the files in our example, modify them and adapt them to your needs.

The Sublim.design content manager includes an image compression script. Much more advanced, it allows you to choose a compression rate for each image and applies to all compressible image formats: jpg, png, WebP and gif.

Download script.php

Script.zip
Back to Top