One of the most appreciated features of PHP is the ability to create and manipulate graphical images using the GD extension functions. This extension comes with all PHP distributions, so everybody can use it. You can load and save images in several formats and process them in a way that is convenient to your PHP applications.

Sometimes the available disk space is scarce and it is necessary to minimize the size that the image files take on the server disk. Some time ago I replied to a post from an user that had that problem. He wanted to assure that the JPEG images uploaded to his server did not exceed a given size limit per image.

The PHP GD function imagejpeg takes an optional argument to control the quality factor of the JPEG images generated by the function. The quality factor is a measure of the fidelity of the generated image in comparison with the original image. A lower quality factor leads to the generation of smaller JPEG files.

However, there is no predictable relation between the quality factor and the resulting JPEG image file size. If you want to generate JPEG images with a limited file size, and at the same time you do not want to sacrifice too much the image quality, you have to find an approximated value for the quality factor that leads to an image with a file size near the desired limit.

Huda ElmatsaniThat is the approach used by the JPEG Reducer class written by Huda Elmatsani from Indonesia. He wrote the class precisely with the intention of solving this optimization problem.

First the class determines the file size that image would take using 3 different quality factor values. Then it uses interpolation to find an approximate quality factor that matches the desired image file size limit.

The class usage is very straightforward. It just takes a JPEG image file name and the desired file size limit. The resulting image may be stored in another server side file or served as the current script output. Here is an example:

require("class.jpegreducer.php");

$im = new JPEGReducer("jakarta.jpg", 10000);
$im->OutputImage("jakarta1.jpg");

 

Simple, but brilliant. That is why this class won the PHP Programming Innovation Award edition of November 2004.