Reducing image size on digital photos - PHP
Archive - Originally posted on "The Horse's Mouth" - 2010-01-17 10:01:15 - Graham Ellis
Using PHP and the GD library, I'm copying and resizing images that would be over a quarter of a megabyte to download, using the following code, which you'll note maintains the aspect ratio, and limits the image to a maximum of 800 pixels wide, and 600 pixels tall.
if (filesize($fx) > 256000) {
$in_img = imagecreatefromjpeg($fx);
$width = $in_width = imagesx( $in_img );
$height = $in_height = imagesy( $in_img );
if ($width > 800) {
$height = $height * 800 / $width;
$width = 800;
}
if ($height > 600) {
$width = $width * 600 / $height;
$height = 600;
}
$img = imagecreatetruecolor( $width, $height );
imagecopyresized( $img, $in_img, 0, 0, 0, 0, $width, $height, $in_width, $in_height );
imagejpeg($img, "thumbs/$fx" );
$instr = fopen("thumbs/$fx","rb");
$imagebytes = fread($instr,filesize("thumbs/$fx"));
} else {
$instr = fopen($fx,"rb");
$imagebytes = fread($instr,filesize($fx));
}
I have used a temporary directory for my reduced size picture (they're not really small enough to be called thumbnails), and the $imagebytes variable gets sent out later in the PHP script as the response to the http request for the image. We're also (a story I have told elsewhere) saving the image into a database.
Some more images in the new library ...











