PHP Code

Resize an Image to Create a Thumbnail With PHP

If you are building an image gallery with PHP, or any sort of web application that takes user-supplied images (such as an e-commerce shopping cart in which you upload product photos), it's vital to be able to generate thumbnails of each image. This script will enable you to get the Jpeg image width and height, and create a thumbnail by resizing the image with the same ratio.

By default the maximum width & height of the thumbnails is 125 pixels. You can modify that depending on the needs of your application, just change the $max_width and $max_height variables.

This code assumes the GD support has been compiled with PHP. This is true with most Linux-based hosting providers. This code works for .jpg images only.

$image = "$path_to_images";
$savelocation = "$path_to_thumbnail_dir";
$oldumask = umask(0);
mkdir("$path_to_thumbnail_dir", 0777);
if (!$max_width)
$max_width = 125;
if (!$max_height)
$max_height = 125;
$size = GetImageSize($image);
$width = $size[0];
$height = $size[1];
$x_ratio = $max_width / $width;
$y_ratio = $max_height / $height;
if ( ($width <= $max_width) && ($height <= $max_height) ) { $tn_width = $width; $tn_height = $height; } else if (($x_ratio * $height) < $max_height) { $tn_height = ceil($x_ratio * $height); $tn_width = $max_width; } else { $tn_width = ceil($y_ratio * $width); $tn_height = $max_height; } $src = ImageCreateFromJpeg($image); $dst = ImageCreate($tn_width,$tn_height); ImageCopyResized($dst, $src, 0, 0, 0, 0, $tn_width,$tn_height,$width,$height); ImageJpeg($dst,"$savelocation"."thumb_$file"); ImageDestroy($src); ImageDestroy($dst); [/code] This code was adapted from a posting on Daniweb


Leave a Reply

Your email address will not be published. Required fields are marked *

To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image