I\'m trying to create a Thumbnail Generator in PHP with GD that will take an image and reduce it to a fixed width/height. The square it takes from the original image (based on m
How about this: It's take an image of any size and proportionately resize it down (or up) to fill a canvas of any dimensions.
E.g. Source image is: 400w x 600h and thumbnail size needs to be 100w x 225h - the output image will be 100w x 225h and the images will be vertically centered with a width of 100 (the maximum) and height 150 (with a top and bottom border of 37.5 pixels)
Here's the function
function resize_to_canvas($filename,$canvas_w=100,$canvas_h=225){
list($width, $height, $type) = getimagesize($filename);
$original_overcanvas_w = $width/$canvas_w;
$original_overcanvas_h = $height/$canvas_h;
$dst_w = round($width/max($original_overcanvas_w,$original_overcanvas_h),0);
$dst_h = round($height/max($original_overcanvas_w,$original_overcanvas_h),0);
$dst_image = imagecreatetruecolor($canvas_w, $canvas_h);
$background = imagecolorallocate($dst_image, 255, 255, 255);
imagefill($dst_image, 0, 0, $background);
$src_image = imagecreatefromjpeg($filename);
imagecopyresampled($dst_image, $src_image, ($canvas_w-$dst_w)/2, ($canvas_h-$dst_h)/2, 0, 0, $dst_w, $dst_h, $width, $height);
imagegif($dst_image, $filename);
imagedestroy($dst_image);}
This function will replace the original file but is easily modified to create a new thumbnail image. Just change the file name the line imagegif($dst_image, $filename);
I'm sorry if I'm offering an indirect answer. But you could try using this library: PHPThumb. It's very easy to use. It supports GD and has this function called adaptive resizing which resizes the image from the center.
Here's a sample code from the docs for adaptive resizing:
<?php
require_once 'path/to/ThumbLib.inc.php';
try
{
$thumb = PhpThumbFactory::create('/path/to/image.jpg');
}
catch (Exception $e)
{
// handle error here however you'd like
}
$thumb->adaptiveResize(175, 175);
$thumb->show();
?>
Is this what you're looking for:
Crop-To-Fit an Image Using ASP/PHP
The script can be used to create square thumbnails out of portrait/landscape images. The solution requires two steps:
1: resize the image proportionally so that one of the dimension matches the desired dimension while other is equal or greater.
2: crop from the middle of the image; the math is simple.
Without a clear and well-defined goal, it is hard to try and offer a well-suited solution. Also, you will tend to find other Stackers more helpful if you at least bring an attempt at a solution to the table.
That being said, I have found a couple of tutorials online which may at least give you an idea to start with - give it a go, and, if you still have troubles, feel free to post further questions (with code samples and details of what is not behaving itself).