Recommended:

  • phpclasses.org
  • jsclasses.org
  • jsmag.com
  • siteapps.com
  • View our reviews on Hot Scripts
  • JS Tutorial
  • scripts.com
  • securesignup.com




Recent Comments

Powered by Disqus




Back to articles

Create thumbnails for image files

This function creates thumbnails for images. It takes image path with file name, thumbnail width, thumbnail height and path where to save thumbnail as parameters.

<?php
function thumb($path, $width = 120, $height = 100, $dest = "./thumbs")
{
    //getting image sizes
    $img_sizes = getimagesize($path);
    //sizes for calculation
    $oldwidth = $img_sizes[0];
    $oldheight = $img_sizes[1];
    //size for resizing
    $bigw = $oldwidth;
    $bigh = $oldheight;
    //simple resizing, minimize proportions and cut off remaining things
    if($oldwidth > 0 && $oldheight > 0){
        if($oldwidth > $oldheight) {
            $x = ceil(($oldwidth - $oldheight) / 2 );
            $oldwidth = $oldheight;
            $y = 0;
            } elseif($oldheight> $oldwidth) {
            $y = ceil(($oldheight - $oldwidth) / 2);
            $oldheight = $oldwidth;
            $x = 0;
        }
        //getting file name
        $tname = explode("/", $path);
        //getting extension
        $ext = explode(".", $tname[sizeof($tname)-1]);
        //if gif
        if($ext[1] == "gif"){
            $img = imagecreatefromgif($path);
            $tmp_img = imagecreatetruecolor( $width, $height );
            imagecopyresampled( $tmp_img, $img, 0, 0, $x, $y, $width, 
                                $height, $oldwidth , $oldheight );
            $thumb = $dest."/".$tname[sizeof($tname)-1];
            imagegif( $tmp_img, $thumb );
        //if png
        }else if($ext[1] == "png"){
            $img = imagecreatefrompng($path);
            $tmp_img = imagecreatetruecolor( $width, $height );
            imagecopyresampled( $tmp_img, $img, 0, 0, $x, $y, $width, 
                                $height, $oldwidth , $oldheight );
            $thumb = $dest."/".$tname[sizeof($tname)-1];
            imagepng( $tmp_img, $thumb );
        }
        //other files as jpg and jpeg
        else{
            $img = imagecreatefromjpeg($path);
            $tmp_img = imagecreatetruecolor( $width, $height );
            imagecopyresampled( $tmp_img, $img, 0, 0, $x, $y, $width, 
                                $height, $oldwidth , $oldheight );
            $thumb = $dest."/".$tname[sizeof($tname)-1];
            imagejpeg( $tmp_img, $thumb );
        }
    }
    //return path with file name
    return $thumb;
}
?>

You may also be interested in:

Powered by BlogAlike.com

blog comments powered by Disqus