Location: PHPKode > scripts > JPEG Reducer > jpeg-reducer/class.jpegxreducer.php
<?php
/**
 * JPEGXReducer class version 1
 * 25 November 2004
 * reduce size of jpeg file on the fly
 * Author: huda m elmatsani
 * Email : justhuda ## netscape ## net
 *
 * Description:
 * This class is variant of JPEGReducer for simplification in usage
 *
 * sintax:
 * JPEGXReducer::Image(jpeg_file_path, expected_size);
 *
 * example
 * JPEGXReducer::Image("jakarta.jpg",15000);
 *
 *
 */

Class JPEGXReducer {

    var $imgname;
    var $imgsize;

    function Image($imgname,$imgsize) {
        $this->imgname = $imgname;
        $this->imgsize = $imgsize;
        $orgsize = filesize($imgname);

        $im         = JPEGXReducer::LoadJpeg();

        header("Content-type: image/jpeg");
        if($imgsize < $orgsize){
            $Qfactor    = JPEGXReducer::CalculateQFactor();
            imagejpeg($im,'',$Qfactor);
        } else {
            imagejpeg($im);
        }


    }

    //courtesy vic at zymsys dot com
    function LoadJpeg () {
        $imgname = $this->imgname;
        $im = @imagecreatefromjpeg ($imgname); /* Attempt to open */
        if (!$im) { /* See if it failed */
    	   $im  = imagecreate (150, 30); /* Create a blank image */
    	   $bgc = imagecolorallocate ($im, 255, 255, 255);
    	   $tc  = imagecolorallocate ($im, 0, 0, 0);
    	   imagefilledrectangle ($im, 0, 0, 150, 30, $bgc);
    	   /* Output an errmsg */
    	   imagestring ($im, 1, 5, 5, "Error loading $imgname", $tc);
        }
        return $im;
    }

    function CalculateQFactor()  {

        $im   = JPEGXReducer::LoadJpeg();
        $size = $this->imgsize;

        //create sample data of 75%, 50%, and 25% quality
        ob_start();
        imagejpeg($im,'',75);
        $buff75 = ob_get_contents();
        ob_end_clean();

        ob_start();
        imagejpeg($im,'',50);
        $buff50 = ob_get_contents();
        ob_end_clean();

        ob_start();
        imagejpeg($im,'',25);
        $buff25 = ob_get_contents();
        ob_end_clean();

        //calculate size of each image
        $size75 = strlen($buff75);
        $size50 = strlen($buff50);
        $size25 = strlen($buff25);

        //calculate gradient of size reduction by quality
        $mgrad1 = 25/($size50-$size25);
        $mgrad2 = 25/($size75-$size50);
        $mgrad3 = 50/($size75-$size25);
        $mgrad  = ($mgrad1+$mgrad2+$mgrad3)/3;

        //result of approx. quality factor for expected size
        return round($mgrad*($size-$size50)+50);
    }

}
?>
Return current item: JPEG Reducer