Image Compression Using Php

Aim
Php has a fair amount of image manipulating functions, but none that really offer any kind of image compression. By image compression we mean sacrificing the quality of the image for faster load times by reducing the size of the image.

The aim is to make a fast and simple function, without the need for temporary files, and without the need to create additional temporary images for interpolation.

Method
The problem is that there is no way to get the 'quality' out of a jpeg, so we estimate the quality based on some assumptions. We also do not try to compress images that are less than 2Mb because the resulting files are usually bigger that the input files. 
 1. <?php
 2. ini_set('display_errors', 1); 
 3. ini_set('log_errors', 1); 
 4. error_reporting(E_ALL);
 5. 
 6. function LossifyJpegImage(& $data){
 7.     $size=strlen($data);
 8.     if($size<2048){
 9.         echo $data;
10.     }
11.     else if(($im = imagecreatefromstring($data))!==FALSE){
12.         $x = imagesx ($im);
13.         $y = imagesy ($im);
14.         $ratio = intval(($size*100)/($y*$x));
15.         $quality = intval(log($ratio)/0.043);
16.         imagejpeg($im, NULL, intval($quality/2));
17.         file_put_contents('php://stderr', "size $size, assumed quality $quality\n");
18.         imagedestroy($im);
19.     }else{
20.         echo $data;
21.     }
22. }
23. 
24. $binary_data = file_get_contents($argv[1]);
25. 
26. LossifyJpegImage($binary_data);
27. ?>
Hide line numbers

Now run the sccript giving it a filename on the command line and pipe the output to a file.

..workspace>php compression.php oldfile.jpg > newfile.jpg

The algorithm is modelled very simply and it is based on empirical tests. It is assumed that it holds true for most images. It is based on this equation that the quality of the image is ascertained.

No comments: