Log in

View Full Version : What is the best way to resize an image?



james438
04-25-2009, 12:30 AM
How can I resize an image to be smaller and retain the highest possible image quality? For example I could use the following:

<?php
$img = 'http://www.mysite/myimage.jpg';
$width = 300px;
$height = '';

// Content type
header('Content-type: image/jpeg');

// Get new dimensions
list($width1, $height1) = getimagesize($img);
if ($width =='') {$j=$height/$height1; $width = $width1 * $j;}
if ($height=='') {$j=$width/$width1; $height = $height1 * $j;}
$new_width = $width;
$new_height = $height;

// Resample
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($img);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width1, $height1);

// Output
imagejpeg($image_p, null, 100);
$img=preg_replace('/h.*\//','',$img);
$img=strtolower($img);
$dest='../images/thumbs/$img';
imagejpeg($image_p,$dest);
?>
but the image quality seems somewhat decreased compared to

<img src='/images/fullsize/myimage.jpg' width=300 alt=''>

The above code was hastily copied from my site. I got this code mostly from php.net

mada9369
04-30-2009, 10:47 PM
imagejpeg($image_p, null, 100);

imagejpeg($image_p,$dest);

why do you have both? :O

djr33
05-01-2009, 04:57 AM
imagecopyresampled() is the correct function. Obviously you'll want to input high quality and output high quality (PNG is "lossless", JPG will lose some quality, but not much at a very high setting), and beyond that it's just setup stuff. The actual dimensions are just math and imagecopyresampled() will handle the "quality" during the resizing, so there's not much to worry about there.