Back to the snippets index

Crop an image ( Anthony 14/6/2008 )

Method to crop an image.

GD code:

<?php
// Crop dimensions.
$width 100;
$height 100;

// Set the path to the image to resize
$input_image "House.jpg";

// Get the size of the original image into an array
$size getimagesize$input_image );

// Prepare canvas
$canvas imagecreatetruecolor$width$height );

// Create a new image in the memory from the file 
$cropped imagecreatefromjpeg$input_image );

// Prepare image  crop - center the crop on the image
$newwidth $size[0] / 2;
$newheight $size[1] / 2;
$cropLeft = ( $newwidth/) - ( $width/);
$cropHeight = ( $newheight/) - ( $height/);

// Generate the cropped image
imagecopyresized$canvas$cropped0,0$cropLeft$cropHeight$size[0], $size[1], $newwidth$newheight );

// Save the cropped image as cropped.jpg
imagejpeg$canvas"cropped.jpg" );

// Clear the memory of the tempory images
imagedestroy$canvas );
imagedestroy$cropped );
?>

Change a png to a jpg
Create some text as an image
Crop an image
Display image without saving
Grayscale image
Resize an image
Rotate an image
Watermark an image