Avatar of hankknight
hankknight
Flag for Canada

asked on 

GD: Exact Canvas size

I want my PHP/GD code to make a thumbnail that is EXACTLY 200px tall by 200px wide.  

The image should remain proportional. The canvas behind the image should be white.

For example, an image that is 800px wide and 200px tall should be resized to be 200px wide by 50px tall, but with 150px of white space below the image.
<?php 
 		echo '<img src="'.
 createthumb('image.jpg','thumb.jpg',200,200,'jpg')
 		.'" alt="" />';
 
function createthumb($imageName,$thumbName,$new_w,$new_h, $typeThumb=null)
{
   if (function_exists('imagecopyresampled')) {
 
	$typeImage = strtolower(pathinfo($imageName, PATHINFO_EXTENSION));
	if($typeThumb===null) $typeThumb = strtolower(pathinfo($thumbName, PATHINFO_EXTENSION));
 
	$typeImage=strtolower($typeImage);
	$typeThumb=strtolower($typeThumb);
 
	if($typeImage==='gif' && !function_exists('imagecreatefromgif')) return;
 
	ignore_user_abort();
	set_time_limit(0);
 
	if ($typeImage==='jpg'||$typeImage==='jpeg')  $src_img=@imagecreatefromjpeg($imageName);
	elseif ($typeImage==='png') $src_img=@imagecreatefrompng($imageName);
	elseif ($typeImage==='gif') $src_img=@imagecreatefromgif($imageName);
	else return $imageName;
 
	$old_x=@imageSX($src_img);
	$old_y=@imageSY($src_img);
 
	if((($new_w<=0) or !is_numeric($new_w)) || (($old_x<=0) or !is_numeric($old_x)) || (($new_h<=0) or !is_numeric($new_h)) || (($old_y<=0) or !is_numeric($old_y))) return $imageName;
 
	$ratio=min($new_w/$old_x,$new_h/$old_y);
	$thumb_w=(int) ($ratio*$old_x+.5);
	$thumb_h=(int) ($ratio*$old_y+.5);
 
	$dst_img=@ImageCreateTrueColor($thumb_w,$thumb_h);
	@imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y); 
 
	if ($typeThumb==='png')
		@imagepng($dst_img,$thumbName); 
	elseif ($typeThumb==='gif')
		@imagegif($dst_img,$thumbName); 
	elseif ($typeThumb==='jpg' || $typeThumb==='jpeg')
		@imagejpeg($dst_img,$thumbName); 
	else return $imageName;
 
	@imagedestroy($dst_img); 
	@imagedestroy($src_img); 
 
	return $thumbName;
  
   }
	else {
	return $imageName;
	}
}
  
?>

Open in new window

PHP

Avatar of undefined
Last Comment
prokvk

8/22/2022 - Mon