PHP Thumbnailer

turt2live 0 Tallied Votes 574 Views Share

What this script does is take in an image and export a thumbnailed version.


Function Arguments:
$file : Desired image to create a thumbnail of
$destination : End location for the thumbnail
$zoom : Setting type, explained later (default: false)
$t_width : Thumbnail width (default: 150)
$t_height : Thumbnail height (default: 150)


This script is capable of making 2 types of thumbnails:

  1. Cropped to fit (Small Preview)
  2. Resized (Fit Width)

A sample of this script is here:

If you would like the "Cropped to fit (Small Preview)" then set $zoom = true, otherwise, set it to false.

<?php
function create_thumbnail($file, $destination, $zoom = false, $t_width = 150, $t_height = 150){
	$image_source =			getimagesize($file);	
	$source_mime = 			$image_source['mime'];
	$source_x = 			$image_source[0];
	$source_y = 			$image_source[1];
	
	if($source_mime == "image/png"){
		$image = imagecreatefrompng($file);
	}else if($source_mime == "image/jpeg"){
		$image = imagecreatefromjpeg($file);
	}else if($source_mime == "image/gif"){
		$image = imagecreatefromgif($file);
	}
	
	//Zoom means "crop", else means "resize"
	if($zoom == true){
		$crop_x = 		floor($source_x / 2) - floor($t_width / 2);
		$crop_y = 		floor($source_y / 2) - floor($t_height / 2);
		
		if($crop_x < 0){
			$crop_x = 0;
		}
		if($crop_y < 0){
			$crop_y = 0;
		}
		if (($source_x - $crop_x) < $t_width){
			$t_width = $source_x - $crop_x;
		}
		if (($source_y - $crop_y) < $t_height){
			$t_height = $source_y - $crop_y;
		}
		
		$export_image = imagecreatetruecolor($t_width, $t_height);
		imagecopy($export_image, $image, 0, 0, $crop_x, $crop_y, $source_x, $source_y);
		imagepng($export_image, $destination);
	}else{
		$ratio = 			$t_width / $source_x;
		$t_height = 		$source_y * $ratio;
		$export_image = 	imagecreatetruecolor($t_width, $t_height);
		
		imagecopyresized($export_image, $image, 0, 0, 0, 0, $t_width, $t_height, $source_x, $source_y);
		imagepng($export_image, $destination);
	}
	
	return $destination;
}
?>

Dani AI

Generated

Practical notes and fixes for ’s thumbnailer (and context from ’s Imagick suggestion).

The posted function implements both “crop” and “resize” modes but has several real-world issues that commonly break thumbnails for user uploads: the crop path copies the full source width/height instead of the target thumb size (produces wrong results), resizing uses imagecopyresized (low quality), PNG/GIF alpha is not preserved, EXIF orientation from phones is ignored, return/error handling is missing, resources are never freed, and output is forced to PNG regardless of original format. ’s point about Imagick is sound — it handles more formats (PSD, animated GIFs), offers higher-quality filters and simpler crop/resize APIs — but a robust GD fallback is still useful on many hosts.

Core fixes (compact example of the corrected GD approach):

/* preserve transparency for PNG/GIF */
imagealphablending($dst, false);
imagesavealpha($dst, true);

/* high-quality resize */
imagecopyresampled($dst, $src, 0, 0, 0, 0, $dst_w, $dst_h, $src_w, $src_h);

/* correct center-crop copy: copy $dst_w x $dst_h from $crop_x,$crop_y */
imagecopy($dst, $src, 0, 0, $crop_x, $crop_y, $dst_w, $dst_h);

/* save in matching format and free memory */
imagejpeg($dst, $path, 85); // use imagepng for PNGs
imagedestroy($src);
imagedestroy($dst);

Additional recommendations: validate getimagesize() return and the MIME via finfo_file() before processing; handle EXIF orientation for JPEGs (read orientation and rotate with imagerotate()); limit input dimensions or queue very large images to avoid memory exhaustion; detect and handle animated GIFs separately or prefer Imagick when animation must be preserved; return clear success/error values rather than always returning the destination path. These changes yield better-quality, safer thumbnails and complement ’s Imagick option when available.

cwarn23 387 Occupation: Genius Team Colleague Featured Poster

The code in the snippet is an example of how terrible the gd library is at the best of times when dealing with photos users have uploaded. That is why it is best to use the Imagick module whenever possible. It is faster, in oop and after a while becomes easier to use than gd. For example I have prepared the following script which loads a psd image which would be impossible in gd then resizes it, saves it to a file and displays the picture to the browser.

<?php
$file='images/banner.psd'; //yes this format is accepted
$width=96;
$height=72;

//load image
$thumb = new Imagick($file);

//resize image
$thumb->resizeImage($width,$height,Imagick::FILTER_LANCZOS,1);

//save image to file
$thumb->writeImage('mythumb.gif');

//convert image to jpeg
$thumb->setImageFormat('jpeg');
$thumb->setImageCompressionQuality(100);

//display image to browser
header("Content-type: image/jpeg");
echo $thumb->getImageBlob();

//remove from memory
$thumb->clear();
$thumb->destroy(); 

?>

Note that you can insert any image type that you like into the Imagick() parameter and it will accept it. No if statements, no mime types, just insert and go. So much more simpler.

Matthew N. 0 Junior Poster in Training

cwarn23, in your code I cannot see what variable image is equal t.
Could you please explain

cwarn23 387 Occupation: Genius Team Colleague Featured Poster

Did you mean $image because check again, there is no variable image ;)

turt2live 5 Junior Poster in Training

cwarn32, I appreciate your code, but it does not allow for a smaller "preview" of the image, do you know how you could use your suggestion to compensate for this?

cwarn23 387 Occupation: Genius Team Colleague Featured Poster

cwarn32, I appreciate your code, but it does not allow for a smaller "preview" of the image, do you know how you could use your suggestion to compensate for this?

My code resizes the image and displays it allowing for a smaller preview. So please describe what exactly it is your after as my code already fits that description.

turt2live 5 Junior Poster in Training

If you go to the sample link I provided on my code it gives you 2 thumbnails:

One that resizes and one that crops the image to a certain area.

Your code does the resize, but not the crop.

cwarn23 387 Occupation: Genius Team Colleague Featured Poster

well to crop you simply add the following code:

$thumb->cropImage($width,$height,$x,$y);
turt2live 5 Junior Poster in Training

Alright, thank you :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.