Want some programming help? [close]

How to Crop Images with PHP GD and Imagick

Two common libraries for image manipulation with PHP are GD and Imagick. GD typically comes with most PHP setups. Here are some code snippets that demonstrate how to crop an image with both libraries.

GD

$src_img = imagecreatefrompng('300x200.png');
if(!$src_img) {
    die('Error when reading the source image.');
}
$thumbnail = imagecreatetruecolor(200, 200);
if(!$thumbnail) {
    die('Error when creating the destination image.');
}
// Take 200x200 from 200x200 starting at 50,0
$result = imagecopyresampled($thumbnail, $src_img, 0, 0, 50, 0, 200, 200, 200, 200);
if(!$result) {
    die('Error when generating the thumbnail.');
}
$result = imagejpeg($thumbnail, '200x200gd.png');
if(!$result) {
    die('Error when saving the thumbnail.');
}
$result = imagedestroy($thumbnail);
if(!$result) {
    die('Error when destroying the image.');
}

Imagick

$inFile = "300x200.png";
$outFile = "200x200_imagick.png";
$image = new Imagick($inFile);
$image->cropImage(200,200, 50,0);
$image->writeImage($outFile);

Advertisement