Tuesday 26 June 2012

Cropping An Image with PHP and the GD Library


Cropping an image with PHP shouldn’t terribly difficult to do and yet when I attempted to do so several months back I was amazed at how little useful documentation PHP offered. Upon Googling the topic I was further amazed but the lack of useful tutorials on the subject. The few I found were overly complicated and didn’t cover simple image cropping. After reading up as much as I could on the subject, and some trial and error, I was able to accomplish my goal of cropping an image with PHP using the GD library.
Just this morning an online friend of mine was struggling with the same issue and twittered for some advice and guidance. I sent them the core of the code I wrote and wished them good luck. I received a quick reply that it worked perfectly for them and apparently ended two days of hair pulling. So I decided I would post the code I sent them here so anyone else who is looking to crop images with PHP and the GD library can do so without having to endure limited documentation and inventing swear words.


// Original image
$filename = 'someimage.jpg';

// Get dimensions of the original image
list($current_width, $current_height) = getimagesize($filename);

// The x and y coordinates on the original image where we
// will begin cropping the image
$left = 50;
$top = 50;

// This will be the final size of the image (e.g. how many pixels
// left and down we will be going)
$crop_width = 200;
$crop_height = 200;

// Resample the image
$canvas = imagecreatetruecolor($crop_width, $crop_height);
$current_image = imagecreatefromjpeg($filename);
imagecopy($canvas, $current_image, 0, 0, $left, $top, $current_width, $current_height);
imagejpeg($canvas, $filename, 100);
// Original image
$filename = 'someimage.jpg';

// Get dimensions of the original image
list($current_width, $current_height) = getimagesize($filename);

// The x and y coordinates on the original image where we
// will begin cropping the image
$left = 50;
$top = 50;

// This will be the final size of the image (e.g. how many pixels
// left and down we will be going)
$crop_width = 200;
$crop_height = 200;

// Resample the image
$canvas = imagecreatetruecolor($crop_width, $crop_height);
$current_image = imagecreatefromjpeg($filename);
imagecopy($canvas, $current_image, 0, 0, $left, $top, $current_width, $current_height);
imagejpeg($canvas, $filename, 100);
Hopefully that helps demonstrate how to simply crop an image with PHP and the GD library.

No comments:

Post a Comment