I need to resize a picture to a fixed size. But it has to keep the factors between the width and height.
Say I want to resize a picture from 238 (w) X 182 (
I'd much rather resize so that the image is contained within your limit and then fill out the blank parts. So in the above example you would resize so that the height is OK, then fill up (7 pixels on each end I think) to the left and right with a background color.
This doesn't crop the picture, but leaves space around the new image if necessary, which I think is a better approach (than cropping) when creating thumbnails.
$w = 210;
$h = 150;
$orig_w = imagesx($original);
$orig_h = imagesy($original);
$w_ratio = $orig_w / $w;
$h_ratio = $orig_h / $h;
$ratio = $w_ratio > $h_ratio ? $w_ratio : $h_ratio;
$dst_w = $orig_w / $ratio;
$dst_h = $orig_h / $ratio;
$dst_x = ($w - $dst_w) / 2;
$dst_y = ($h - $dst_h) / 2;
$thumbnail = imagecreatetruecolor($w, $h);
imagecopyresampled($thumbnail, $original, $dst_x, $dst_y,
0, 0, $dst_w, $dst_h, $orig_w, $orig_h);
Maybe take look at PHPThumb (it works with GD and ImageMagick)
Just a tip for high-quality fast thumbnail generation from large images: (from the php.net site)
If you do the thumbnail generation in two stages:
then this can be much faster; the resize in step 1 is relatively poor quality for its size but has enough extra resolution that in step 2 the quality is decent, and the intermediate image is small enough that the high-quality resample (which works nicely on a 2:1 resize) proceeds very fast.
Resizing images from within a PHP-sourced webpage can be problematic. Larger images (approaching 2+MB on disk) can be so large that they need more than 32MB of memory to process.
For that reason, I tend to either do it from a CLI-based script, with up-to 128MB of memory available to it, or a standard command line, which also uses as much as it needs.
# where to put the original file/image. It gets resized back
# it was originally found (current directory)
SAFE=/home/website/PHOTOS/originals
# no more than 640x640 when finished, and always proportional
MAXSIZE=640
# the larger image is in /home/website/PHOTOS/, moved to .../originals
# and the resized image back to the parent dir.
cd $SAFE/.. && mv "$1" "$SAFE/$1" && \
convert "$SAFE/$1" -resize $MAXSIZE\x$MAXSIZE\> "$1"
'convert' is part of the ImageMagick command line tools.
Do you have Imagick? If so you can load the image with it and do something like thumbnailimage()
There you can skip either of the parameters (height or width) and it will resize correctly.