chx
chx

Reputation: 11790

How to scale-and-crop with imagemagick convert?

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?

Upvotes: 8

Views: 11643

Answers (1)

chx
chx

Reputation: 11790

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

Upvotes: 22

Related Questions