Pages

Sunday, February 19, 2012

Thumbnail generation of 3 types of images (jpeg, gif and png)

Here is a code block used in a cakephp controller to generate thumbnails of 3 types of images:
I have used the extract function and the output for the pathinfo funciton.

The parameter $file receives the full system path+filename
$id - is used in part of the thumbnail name since each file has a record in db on my app

    function makeThumb($file, $id ) {
        extract( pathinfo($file) );
        //$dirname, $basename, $extension, $filename
       
        // Get new sizes
        list($width, $height) = getimagesize($file);
        $newheight = 180;//$height * $percent;
        $newwidth = $width/$height*$newheight;

        // Load
        $thumb = imagecreatetruecolor($newwidth, $newheight);
        switch(  $extension ) {
            case 'jpg': $source = imagecreatefromjpeg($file); break;
            case 'gif': $source = imagecreatefromgif($file); break;
            case 'png': $source = imagecreatefrompng($file); break;
        }
        // Resize
        imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
        // Output
        $name = 'thumb_'.$id.'.'.$extension;
        switch( $extension  ) {
            case 'jpg': imagejpeg($thumb, $dirname.'/'.$name, 100); break;
            case 'gif': imagegif($thumb, $dirname.'/'.$name, 100); break;
            case 'png': imagepng($thumb, $dirname.'/'.$name, 100); break;
        }
    }

No comments :

Post a Comment