<?php

/******************************************************************
*   Name:       
*       PHP Class thumbJPEG
*   Description:
*       generate cached thumbnail from JPEG filename resampled 
*       to 0-100 percent of the original size.
*   Usage:
*       <?php
*       require("thumbJPEG.php");
*       // resize 'any_file.jpg' to 15% and output picture.
*       new thumbJPEG("any_file.jpg", 15); 
*       ?>
*   Released:   
*       Sun Feb 24 11:02:16 CET 2008
*   Updated:
*       Wed Jul 23 21:00:40 CEST 2008
*   Author:     
*       Etilem      <http://www.etilem.net/contact>
*   Copyright:  
*       GLPv3       <http://www.gnu.org/licenses/gpl-3.0.html>
******************************************************************/

class thumbJPEG {

    var 
$im;
    var 
$file;
    var 
$coef;
    var 
$hash;

    function 
errorJPEG ($msg) {
        
$wd         strlen ($msg) * 10;
        
$hg         50;
        
$bgc        51;
        
$fgc        204;
        
$err        = @imagecreatetruecolor($wd$hg);
        
$bgc        = @imagecolorallocate($err$bgc$bgc$bgc);
        
$tcc        = @imagecolorallocate($err$fgc$fgc$fgc);
        @
imagefilledrectangle($err00$wd$hg$bgc);
        @
imagestring($err5$wd/20$hg/3$msg$tcc);
        
$this->im   $err;
    }

    function 
genJPEG () {
        if (
$this->is_cached ()) {
            
$this->im = @imagecreatefromjpeg ($this->get_cfile());
        } else {
           list(
$w$h) = @getimagesize ($this->file);
            
$nw         $w $this->coef;
            
$nh         $h $this->coef;
            
$dest       = @imagecreatetruecolor ($nw$nh);
            
$this->im   = @imagecreatefromjpeg ($this->file);
            @
imagecopyresampled ($dest$this->im0000$nw$nh$w$h);
            if (
$this->im $dest) {
                
$dir dirname($this->get_cfile()); 
                if (!
file_exists($dir)) mkdir($dir);
                
imagejpeg ($this->im$this->get_cfile());
            } else {
                
$this->errorJPEG ("<! ERROR !>");
            }
        }
    }

    function 
getJPEG () {
        
$this->genJPEG ();
        
header ("Content-Type: image/jpeg");
        return 
imagejpeg ($this->im);    
    }

    function 
getHash () {
        return 
md5 (sprintf ("file:%s:coef:%s"$this->file$this->coef));
    }

    function 
get_cfile ($ext "jpg") {
        return 
sprintf (".cache/%s.%s"$this->hash$ext);
    }

    function 
is_cached () {
        return 
file_exists ($this->get_cfile());
    }

    function 
__construct($fn$c) {
        
$this->file $fn;
        
$this->coef $c $c 100 1;
        
$this->hash $this->getHash ();
        
$this->getJPEG ();
    }
}
?>