Thumbnail image creation using php code

In this post explains how to create thumbnail image using php code.

function make_thumb($img_name,$filename,$new_w,$new_h)
{
//get image extension.
$ext=getExtension($img_name);
//creates the new image using the appropriate function from gd library
if(!strcmp(“jpg”,$ext) || !strcmp(“JPG”,$ext) || !strcmp(“jpeg”,$ext) || !strcmp(“JPEG”,$ext))
$src_img=imagecreatefromjpeg($img_name);

if(!strcmp(“gif”,$ext) || !strcmp(“GIF”,$ext))
$src_img=imagecreatefromgif($img_name);

if(!strcmp(“png”,$ext) || !strcmp(“PNG”,$ext))
$src_img=imagecreatefrompng($img_name);

//gets the dimmensions of the image
$old_x=imagesx($src_img);
$old_y=imagesy($src_img);

$ratio1=$old_x/$new_w;
$ratio2=$old_y/$new_h;

if($ratio1>$ratio2) {
$thumb_w=$new_w;
$thumb_h=$old_y/$ratio1;
}
else {
$thumb_h=$new_h;
$thumb_w=$old_x/$ratio2;
}
// we create a new image with the new dimmensions
$dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);

// resize the big image to the new created one
imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);

// output the created image to the file. Now we will have the thumbnail into the file named by $filename
if(!strcmp(“png”,$ext))
imagepng($dst_img,$filename);
if(!strcmp(“gif”,$ext))
imagegif($dst_img,$filename);
else
imagejpeg($dst_img,$filename);

//destroys source and destination images.
imagedestroy($dst_img);
imagedestroy($src_img);
}

?>

To find out the extension of image with following function:

function getExtension($str) {
$i = strrpos($str,”.”);
if (!$i) { return “”; }
$l = strlen($str) – $i;
$ext = substr($str,$i+1,$l);
return $ext;
}

Call the particular thumbnail function like :

make_thumb(‘original.jpg’,’thumb.jpg’,150,250);
echo “Thumbnail created successfully…!!!”;

Anil Kumar Panigrahi

With more than 10 years experience in PHP and Founder of Anil Labs, a blog for PHP and related posts. contributed posts regarding CodeIgniter, CakePHP and Learn PHP online ... Contact : [email protected]

You may also like...

3 Responses

  1. GP Code library
    Create thumbnail image by php
    When we upload large size images on server. Uploaded large images take more time to load on webpage, so we need to show small size images on our webpage. Image thumbnail is a solution to generate uploaded image’s thumbnail to show required size images on our website.
    http://codelibrary.googleplus.co.in/create-thumbnail-image-by-php/

  1. June 3, 2010

    […] Thumbnail image creation using php code « ANIL KUMAR PANIGRAHI 's Blog […]

  2. August 31, 2015

    […] Thumbnail image creation using PHP code […]

Leave a Reply

Your email address will not be published. Required fields are marked *