This code will allow you to create a thumbnail from a segment of the image. In some situations, you want to thumbnail an entire image – but other times, you may want only a piece – for example if you wish to generate square thumbnail images regardless of whether or not the original image is landscape or portrait style.

The basics are as follows:

  1. Resize the image, using the $newthumb size value as the SMALLEST measurement (height in the case of landscape images, width in the case or portrait images). So if you had an original image that is 400 pixels wide and 200 pixels tall, it would set the height to 60 (since 60 is the $newthumb height we’ve used in the example below) and then resize the width down according to whatever ratio is that will contrain the proportions.
  2. Trim off the extra so that the end thumb is 60×60.

$orig_path = ‘/path/to/original/file/’;
$micro_path = ‘/path/to/cropped/file/’;
$imagefilename = ‘myimage.jpg’;

$size = getimagesize($orig_path.$imagefilename);

/**
* new cropped thumbnail sizes
*/
$newthumb_width = 60;
$newthumb_height = 60;

/**
* assign friendlier values to getimagesize data
*/
$orig_width = $size[0];
$orig_height= $size[1];

$width_ratio = ($newthumb_width / $orig_width );
$height_ratio = ($newthumb_height / $orig_height);

if ($orig_width > $orig_height ) {
// this is a landscape image
$crop_width = round($orig_width * $height_ratio);
$crop_height = $newthumb_height;

} elseif ($orig_width < $orig_height ) { // this is a portrait image $crop_height = round($orig_height * $width_ratio); $crop_width = $newthumb_width; } else { // this is a square image $crop_width = $newthumb_width; $crop_height = $newthumb_height; } $source_img = imagecreatefromjpeg($orig_path.$imagefilename); $dest_img = imagecreatetruecolor($newthumb_width,$newthumb_height); /** * if you want to crop from a specific area, for example, if you * want to crop the image from the middle instead of the top left, * you’ll need to do some more math to replace the 0,0,0,0 bits here. */ imagecopyresampled($dest_img, $source_img, 0 , 0 , 0, 0, $crop_width, $crop_height, $orig_width, $orig_height); imagejpeg($dest_img, $micro_path.$imagefilename); imagedestroy($dest_img);[/sourcecode]

ssd-virtual-servers-banner-468x60

Advertisement

Themeforest
Previous post

Dynamic Watermarks/Text Overlay on Images in PHP

Next post

More About register_globals

snipe

snipe

I’m a tech geek/dev/infosec-nerd/scuba diver/blacksmith/sword-fighter/crime fighter/ENTP/warcrafter/activist. I'm the CTO at Mass Mosaic and the CEO of Grokability, Inc. in San Diego, CA. Tweet at me @snipeyhead or read more...