How to create image thumbnail using PHP

04th, January 2018 By

Today we will do how create image thumbnail using php. Once i have worked on my project ,i have faced the situation of create thumbnail of images uploaded on server.Its very easy to create the thumbnail of image .

function thumbnail($source, $destination, $requiredWidth,$fileExtension) {

	/*  The source image */
	if($fileExtension=="jpg" || $fileExtension=="jpeg" ){
              $sourceImage = imagecreatefromjpeg($src);
              else if($fileExtension=="png"){
              $sourceImage = imagecreatefrompng($src);
              $sourceImage = imagecreatefromgif($src);
	$width = imagesx($sourceImage);
	$height = imagesy($sourceImage);

	/* find the height of this thumbnail, relative to the width  */
	$requiredHeight = floor($height * ($requiredWidth / $width));

	/* create thumb image */
	$thumbImage = imagecreatetruecolor($requiredWidth, $requiredHeight);

	/* copy source image at a resized size */
	imagecopyresampled($thumbImage, $sourceImage, 0, 0, 0, 0, $requiredWidth, $requiredHeight, $width, $height);

	/* create the thumbnail image to its destination */
	imagejpeg($thumbImage, $destination);

Here the variable:-

$fileExtension = File extension of the image.

$source = The image source which thumbnail have to create.

$destination = Its the place where image for thumbnail copy.

$requiredWidth = Width for the thumbnail.

This function work for jpg,png,jpeg and gif image extensions.You will easily create thumbnail from your image using this code. Hope this help you.

Leave a Reply

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