how do i use imagick in php? (resize & crop)

newworroo picture newworroo · Aug 19, 2013 · Viewed 31.9k times · Source

I use imagick for thumbnail crop, but sometimes cropped thumbnails are missing top part of the images (hair, eyes).

I was thinking to resize the image then crop it. Also, I need to keep the image size ratio.

Below is the php script I use for crop:

$im = new imagick( "img/20130815233205-8.jpg" );
$im->cropThumbnailImage( 80, 80 );
$im->writeImage( "thumb/th_80x80_test.jpg" );
echo '<img src="thumb/th_80x80_test.jpg">';

Thanks..

Answer

Martin M&#252;ller picture Martin Müller · Aug 19, 2013

This task is not easy as the "important" part may not always be at the same place. Still, using something like this

$im = new imagick("c:\\temp\\523764_169105429888246_1540489537_n.jpg");
$imageprops = $im->getImageGeometry();
$width = $imageprops['width'];
$height = $imageprops['height'];
if($width > $height){
    $newHeight = 80;
    $newWidth = (80 / $height) * $width;
}else{
    $newWidth = 80;
    $newHeight = (80 / $width) * $height;
}
$im->resizeImage($newWidth,$newHeight, imagick::FILTER_LANCZOS, 0.9, true);
$im->cropImage (80,80,0,0);
$im->writeImage( "D:\\xampp\\htdocs\\th_80x80_test.jpg" );
echo '<img src="th_80x80_test.jpg">';

(tested)

should work. The cropImage parameters (0 and 0) determine the upper left corner of the cropping area. So playing with these gives you differnt results of what stays in the image.