Snipe.Net Geeky, sweary things.

Cropped Thumbnails using PHP and the GD Library

C

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.
[sourcecode language=’php’] $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]

About the author

snipe

I'm a tech nerd from NY/CA now living in Lisbon, Portugal. I run Grokability, Inc, and run several open source projects, including Snipe-IT Asset Management. Tweet at me @snipeyhead, skeet me at @snipe.lol, or read more...

By snipe
Snipe.Net Geeky, sweary things.

About Me

I'm a tech nerd from NY/CA now living in Lisbon, Portugal. I run Grokability, Inc, and run several open source projects, including Snipe-IT Asset Management. Tweet at me @snipeyhead, skeet me at @snipe.lol, or read more...

Get in Touch