ImageMagick:如何最小化图像到特定的长宽比? [英] ImageMagick: how to minimally crop an image to a certain aspect ratio?

查看:149
本文介绍了ImageMagick:如何最小化图像到特定的长宽比?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用imagemagick,我希望以最小的方式裁剪图像,以使其适合给定的宽高比.

With imagemagick, I'd like to crop an image, in a minimal fashion, so that it fits a given aspect ratio.

示例:给定一张3038 x 2014像素的图像,我希望将其裁剪为3:2的宽高比.这样生成的图像将是3021 x 2014像素,从原始图像的中心裁剪.

Example: given an image of, say, 3038 x 2014 px, I want to crop it to have a 3:2 aspect ratio. The resulting image would then be 3021 x 2014 px, cropped from the, say, center of the original image.

所以要查找类似convert in.jpg -gravity center -crop_to_aspect_ratio 3:2 out.jpg的命令.

So looking for a command looking something like convert in.jpg -gravity center -crop_to_aspect_ratio 3:2 out.jpg.

推荐答案

1.具体目标分辨率

如果最终的目标是要具有一定的分辨率(例如1920x1080),则可以轻松地使用-geometry,音调/帽子/屋顶/房屋符号(^)和-crop: >

1. Specific target resolution

If your goal at the end is to have a certain resolution (for example 1920x1080) then it's easy, using -geometry, the circumflex/hat/roof/house symbol (^) and -crop:

convert in.jpg -geometry 1920x1080^ -gravity center -crop 1920x1080+0+0 out.jpg

要遍历多个jpg文件:

To loop over multiple jpg files:

for i in *jpg
  do convert "$i" -geometry 1920x1080^ -gravity center -crop 1920x1080+0+0 out-"$i"
done

2.仅长宽比作物

如果要避免缩放,则必须计算Imagemagick外部的裁切边的新长度.这涉及更多:

2. Aspect ratio crop only

If you want to avoid scaling you have to calculate the new length of the cropped side outside of Imagemagick. This is more involved:

aw=16 #desired aspect ratio width...
ah=9 #and height
in="in.jpg"
out="out.jpg"

wid=`convert "$in" -format "%[w]" info:`
hei=`convert "$in" -format "%[h]" info:`

tarar=`echo $aw/$ah | bc -l`
imgar=`convert "$in" -format "%[fx:w/h]" info:`

if (( $(bc <<< "$tarar > $imgar") ))
then
  nhei=`echo $wid/$tarar | bc`
  convert "$in" -gravity center -crop ${wid}x${nhei}+0+0 "$out"
elif (( $(bc <<< "$tarar < $imgar") ))
then
  nwid=`echo $hei*$tarar | bc`
  convert "$in" -gravity center -crop ${nwid}x${hei}+0+0 "$out"
else
  cp "$in" "$out"
fi

我在示例中使用的是16:9,希望对于大多数读者来说,它比3:2更有用.更改解决方案1中出现的1920x1080或解决方案2中的aw/ah变量,以获取所需的宽高比.

I'm using 16:9 in the examples, expecting it to be more useful than 3:2 to most readers. Change both occurences of 1920x1080 in solution 1 or the aw/ah variables in solution 2 to get your desired aspect ratio.

这篇关于ImageMagick:如何最小化图像到特定的长宽比?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆