PHP Function To Generate Image Thumbnail

Following is a PHP function to generate thumbnails for JPEGs and PNGs. You may use the function by sending the image location, thumb location and the needed width.


generate_thumb('uploads/'.$file, 'thumbs/'.$file, 400);

function generate_thumb($file, $thumb, $new_width) {

	list($width, $height, $mime) = getimagesize($file);
	$diff = $width / $new_width;
	$new_height = $height / $diff;
	$im_dest = imagecreatetruecolor($new_width, $new_height);

	if($mime == 2) { // jpeg
		$img = imagecreatefromjpeg($file);
		imagecopyresampled($im_dest, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
		imagejpeg($im_dest, $thumb, 100);		
	}
	else if($mime == 3) { // png
		$img = imagecreatefrompng($file);
		imagealphablending($im_dest, false);
		imagecopyresampled($im_dest, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
		imagesavealpha($im_dest, true);
		imagepng($im_dest, $thumb);
	}
}