Thursday, July 8, 2010

CREATE IMAGE THUMBNAILS USING PHP and GD

The following PHP code will create thumbnail images on the fly and since it uses the PHP GD2 library, you will need an installation of PHP with at least GD 2.0.1 enabled.. Some says that the only drawback to using PHP for image creation is that the thumbnails don’t look as good as thumbnails created in Photoshop or GIMP but this simple block of code would prove them wrong...

("Content-type: image/jpeg");
$image = $_GET['img'];
if(!isset($w) && !isset($h)){
$w = 100; //default width if $w is not set
$h = 125; //default height if $h is not set
}

$x = @getimagesize($image);// get image size
$sw = $x[0];// width
$sh = $x[1];// height
$im = @ImageCreateFromJPEG ($image) or // Read JPEG Image
$im = false; // If image is not JPEG

if (!$im)
readfile($image);// return the actual message if error occurs.
else {
// Create the resized image destination
$thumb = @ImageCreateTrueColor ($w, $h);
// Copy from image source, resize it, and paste to image destination
@ImageCopyResampled ($thumb, $im, 0, 0, 0, 0, $w, $h, $sw, $sh);
// Output resized image
@ImageJPEG ($thumb);
}
?>




No comments: