Thursday, May 31

Resize Images with GD2

I found a bunch of places on the internets that help you with scripts to resize your images with gd2. These are all pretty cool because they resize your images while preserving their aspect ratio. Well I didn't want that so I had to read through the gd2 info on php.net. It's actually fairly simple, once I figured out what I was doing. I'm using a file uploaded from a form. So here's some simple resize code:

$imgrel = '../images/upload/'.basename($_FILES['pic']['name']); //gd wants relative paths
list($width,$height) = getimagesize($imgrel);
if($width<>150 || $height<>188){
$img_src = imagecreatefromjpeg($imgrel);
$img_dst = imagecreatetruecolor(150,188);
$imagecopyresampled($img_dst, $img_src, 0, 0, 0, 0, 150, 188, $width, $height);
imagejpeg($img_dst, $imgrel, 90);
}
There's the option of using imagecopyresized instead of imagecopyresampled, but I did that and it just doesn't look as good. If you don't know why, read this (I did). When I first did this, it wasn't working, but that was because I forgot the imagejpeg(). Oops. By the way, the 90 in that means 90% quality for that jpeg.

So now I suppose you want to resize your images keeping the aspect ratio. Well, I'm just going to share some code I found that seems to work for me. This one is from 9tutorials:
function resizeImage($originalImage, $toWidth, $toHeight){

list($width, $height) = getimagesize($originalImage);
$xscale = $width/$toWidth;
$yscale = $height/$toHeight;

//recalculate new size with default ratio
if($yscale>$xscale){
$new_width = round($width * (1/$yscale));
$new_height = round($height * (1/$yscale));
}else{
$new_width = round($width * (1/xscale));
$new_height = round($height * 1/xscale));
}
$imageResized = imagecreatetruecolor($new_width, $new_height);
$imageTmp = imagecreatefromjpeg($originalImage);
imagecopyresampled($imageResized, $imageTmp, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
}

There we go. Easy as that. If you don't like that one, there's a different one at Netlobo which is the same as one on Travidal

Now just remember when you're doing this that GD2 is pretty process intensive so if you're resizing lots of images or large images, it's probably better to go with something like imagemagick.

No comments: