Site icon SmartTutorials.net

Thumbnail Image Generation From Uploaded Image Using PHP

For some requirement we need to generate thumbnail image from user uploaded image without decreasing image quality.  Here is php script that resizes upload image (whether it small or bigger one ) to the thumbnail size you set.

Note: PHP GD Library enabled in your php.ini file, otherwise it will fatal error.

 

Thumbnail Image Generation From Uploaded Image Using PHP

Here is the full php script which  generates Thumbnail Image From Uploaded Image Using PHP.

function thumbnail($src, $dist, $dis_width = 100 ){

	$img = '';
	$extension = strtolower(strrchr($src, '.'));
	switch($extension)
	{
		case '.jpg':
		case '.jpeg':
			$img = @imagecreatefromjpeg($src);
			break;
		case '.gif':
			$img = @imagecreatefromgif($src);
			break;
		case '.png':
			$img = @imagecreatefrompng($src);
			break;
	}
	$width = imagesx($img);
	$height = imagesy($img);

	$dis_height = $dis_width * ($height / $width);

	$new_image = imagecreatetruecolor($dis_width, $dis_height);
	imagecopyresampled($new_image, $img, 0, 0, 0, 0, $dis_width, $dis_height, $width, $height);

	$imageQuality = 100;

	switch($extension)
	{
		case '.jpg':
		case '.jpeg':
			if (imagetypes() & IMG_JPG) {
				imagejpeg($new_image, $dist, $imageQuality);
			}
			break;

		case '.gif':
			if (imagetypes() & IMG_GIF) {
				imagegif($new_image, $dist);
			}
			break;

		case '.png':
			$scaleQuality = round(($imageQuality/100) * 9);
			$invertScaleQuality = 9 - $scaleQuality;

			if (imagetypes() & IMG_PNG) {
				imagepng($new_image, $dist, $invertScaleQuality);
			}
			break;
	}
	imagedestroy($new_image);
}

 

 

When you are going call thumbnail() function, you need to pass following parameters i.e. src image, distination image location, size of thumbnail image (width = 200). where height is calculated based on the upload image and width you set for thumbnail image.

where

$src = “images/”.$name;
$dist = “images/thumbnail_”.$name;
or

$src = “http://demo.smarttutorials.net/thumbnail/images/”.$name;
$dist = “http://demo.smarttutorials.net/thumbnail/images/thumbnail_”.$name;

thumbnail($src, $dist, 200);

In thumbnail() function, i am getting given image extension (png, jpg or gif). Also do calculate height from given width.

imagecreatetruecolor() :

This imagecreatetruecolor() will create new image for the given dimension.

Refer this php documentation for imagecreatetruecolor

imagecopyresampled();

This imagecopyresampled() function will resize the source image to given distination image size.

imagecopyresampled($source_img, $distination_img, $source_img_x, $source_img_y, $distination_img_x, distination_img_y, $distination_img_width, $distination_img_height, $source_img_width, $source_img_height);

Refer this php documentation for imagecopyresampled

imagepng() or imagejpeg() or imagegif() :

The above functions will save the given image to their image format..

Exit mobile version