Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scale-and-crop with imagemagick convert?

Tags:

imagemagick

Given the following PHP code:

function image_scale_and_crop(stdClass $image, $width, $height) {
  $scale = max($width / $image->info['width'], $height / $image->info['height']);
  $x = ($image->info['width'] * $scale - $width) / 2;
  $y = ($image->info['height'] * $scale - $height) / 2;

  if (image_resize($image, $image->info['width'] * $scale, $image->info['height'] * $scale)) {
    return image_crop($image, $x, $y, $width, $height);
  }
}

To put it in English, first we do a resize keeping the aspect ratio so that the smaller edge of the image becomes the required size then the resulting image is cropped along the longer edge to $width X $height with equal amounts cut on each side (the smaller side won't need cropping).

Is it possible to do this in a single convert command?

like image 304
chx Avatar asked Sep 12 '13 10:09

chx


1 Answers

I believe the answer is convert "$input" -resize "${width}x${height}^" -gravity center -crop "${width}x${height}+0+0" $output.

like image 76
chx Avatar answered Oct 20 '22 23:10

chx