Create thumbnail image in PHP

In most of cases we need to display the thumbnail image in website. In this article am going to explain how to create the thumbnail image in PHP. I have already posted an article called Create thumbnail image dynamically using PHP where we are creating thumbnail on the fly.

Upload and create thumbnail image in PHP

The disadvantage of that type of thumbnail system is whenever you refreshing the page the thumbnail will generate freshly. But in this type of PHP thumbnail system we have to maintain two separate images will occupy more space.

Download FileDemo

//Image Storage Directory
$img = explode('.', $_FILES['thumb_img']['name']);
//Original File
//Thumbnail file name File
$img_thumb = $img_dir . $img_fileName;
$extension = strtolower($img[1]);

//Check the file format before upload
if(in_array($extension , array('jpg','jpeg', 'gif', 'png', 'bmp'))){

//Find the height and width of the image
list($gotwidth, $gotheight, $gottype, $gotattr)= getimagesize($image_filePath); 	

//---------- To create thumbnail of image---------------
if($extension=="jpg" || $extension=="jpeg" ){
$src = imagecreatefromjpeg($_FILES['thumb_img']['tmp_name']);
else if($extension=="png"){
$src = imagecreatefrompng($_FILES['thumb_img']['tmp_name']);
$src = imagecreatefromgif($_FILES['thumb_img']['tmp_name']);

imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight, $width,$height);
//Create thumbnail image

Here you need to change the default width of thumbnail image in $newwidth variable. The height of the image will calculate automatically. I did some calculation the get the new width like below.

$newheight = round (($gotheight*$newwidth)/$gotwidth);

By doing this the image quality and the size will be changed accordingly, and both the original image ans well as the thumbnail image will store in the images folder. If you want you can move the thumbnail image to separate folder. hope that this will help you.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>