Use this script to resize your image to different aspect ratio on the fly. For instance, when you have a 1024x800 wallpaper and you want to create a 120x120 thumbnail of it. This is done by cropping the source image to match the thumbnail's aspect ratio first, then resizing the cropped image to the thumbnail size.
Listing 1: image.php
<?php
/**
* Resize Image with Different Aspect Ratio
*
* Author: Nash
* License: GPL
* Website: http://nashruddin.com
*/
header("Content-type: image/jpeg");
/* get parameters */
$f = $_GET['f'];
$w = $_GET['w'];
$h = $_GET['h'];
/* expand the thumbnail's aspect ratio
to fit the width/height of the image */
$sw = $in[0] / $w;
$sh = $in[1] / $h;
$s = $sw < $sh ? $sw : $sh;
/* crop the center of the image */
$x0 = floor( ( $in[0] - ( $w * $s ) ) * 0.5 ); $y0 = floor( ( $in[1] - ( $h * $s ) ) * 0.5 );
/* support JPG, PNG and GIF */
$im = @imagecreatefromjpeg($f) or
$im = @imagecreatefrompng($f) or
$im = @imagecreatefromgif($f) or
$im = false;
if (!$im) {
/* something went wrong, output the image */
} else {
/* create thumbnail */
$thumb = @imagecreatetruecolor($w, $h);
@imagecopyresampled($thumb, $im, 0, 0, $x0, $y0, $w, $h, ($w * $s), ($h * $s));
@imagejpeg($thumb);
}
All you have to do is save the listing above to image.php, and use it like this:
<img src="image.php?w=120&h=120&f=wallpaper.jpg" border="0" />
Related Articles
Salman on Mar 2, 2009:
http://911-need-code-help.blogspot.com/2008/10/resize-images-using-phpgd-library.html
The entire image is resized to "best fit" in the specified thumbnail width and height.