Creating Thumbnail in PHP

Introduction

In this article I will explain how to create a thumbnail in PHP. To create a thumbnail image, you need the GD library. GD is an open source code library for the dynamic creation of images by programmers. This library for creating a thumbnail has the function named "createthumb()" that has four parameters. To create the thumbnail image, first check the extension and then read in the file using eihter the "imagecreatefromjpg()", "imagecreatefrompng()" or "imagecreatefromgif()" function and then calculate the size of the new thumbnail image. The "imageheight()" and "imagewidth()" functions return the width and height of the image, respectively.
To create a new image, use the "imagecreatetruecolor()" function and finally use the "imagecopyresampled()" function to copy and resize the original file.
thumbnai in php.png

Example

function createthumb($name,$filename,$new_width,$new_height)

{

$system=explode(".",$name);

if (preg_match("/jpg|JPG|jpeg|JPEG/",$system[1])){$src_img=imagecreatefromjpeg($name);}

elseif (preg_match("/png|PNG/",$system[1])){$src_img=imagecreatefrompng($name);}

elseif (preg_match("/gif|GIF/",$system[1])){$src_img=imagecreatefromgif($name);} 

$old_height=imagesheight($src_img);

$old_width=imageswidth($src_img);

if ($old_height > $old_width)

{

$thumb_width=$new_width;

$thumb_height=$old_width*($new_height/$old_height);

}

if ($old_height < $old_width)

{

$thumb_width=$old_height*($new_width/$old_width);

$thumb_height=$new_height;

}

if ($old_height == $old_width)

{

$thumb_width=$new_width;

$thumb_height=$new_height;

}

$dst_img=ImageCreatetrueColor($thumb_width,$thumb_height);

imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_width,$thumb_height,$old_height,$old_width);

if (preg_match("/png/",$system[1]))

{

imagepng($dst_img,$filename);

}

elseif (preg_match("/gif/",$system[1]))

{

imagegif($dst_img,$filename);

}

else{

imagejpeg($dst_img,$filename);

}

imagedestroy($dst_img);

imagedestroy($src_img);

}

<html>

<head>Here is your pic!</head>

<body>

<h2>Your image has been saved!</h2>

<img src="image/<?php echo $_POST['id']; ?> .jpg">

</body>

</html>

You can set the dimensions of the thumbnail. Such as in the following:

$thumb_width=$width * 0.01;

$thumb_height=$height * 0.01;

 

 

 

Up Next
    Ebook Download
    View all
    Learn
    View all