如何使用ImageMagick convert进行缩放和裁剪?

8

以下是PHP代码:

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);
  }
}

简单来说,我们首先按比例调整大小,使图像的较小边缘变为所需大小,然后沿着较长的边缘剪裁出一个尺寸为$width X $height的图像,每一侧都要等量剪裁(较小的一侧不需要剪裁)。

是否可以在一个convert命令中完成这个操作?

1个回答

21
我认为答案是 convert "$input" -resize "${width}x${height}^" -gravity center -crop "${width}x${height}+0+0" $output

3
你也可以使用 -extent 参数:convert $input -resize $widthx$height^ -gravity center -extent $widthx$height $output。该命令用于调整图像大小并添加背景以填充任何空白区域。 - mivk
1
@mivk 你应该把这个作为答案。对我很有效,而被接受的答案则没有用。 - A. Levy
顺便提一下,根据您的需求,您可以添加“-background white”或“-background black”。 - Tom Boutell

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接