Search code examples
phpimagemagickcrop

PHP ImageMagick Crop By Providing top/right/bottom/left Percentages


I know how to crop an image using cropImage() function of ImageMagick:

$imagick->cropImage($width, $height, $startX, $startY);

How can I crop an image using PHP by providing top, right, left and bottom percentages using ImageMagick?


Solution

  • I solved it using the following code:

    $imagick = new Imagick;
    $imagick->readImageBlob( $image );
    
    $image_width    = $imagick->getImageWidth();
    $image_height   = $imagick->getImageHeight();
    
    $x = $image_width * ($left/100);
    $y = $image_height * ($top/100);
    
    $new_width  = $image_width - ($image_width * ($right/100)) - $x;
    $new_height = $image_height - ($image_height * ($bottom/100)) - $y;
    
    $imagick->cropImage($new_width, $new_height, $x, $y);