Kel*_*ert 22 crop imagemagick aspect-ratio
使用imagemagick,我想以最小的方式裁剪图像,以便它适合给定的宽高比.
示例:给出3038 x 2014 px的图像,我想将其裁剪为3:2的宽高比.然后生成的图像将是3021 x 2014 px,从原始图像的中心裁剪出来.
所以寻找一个类似的命令convert in.jpg -gravity center -crop_to_aspect_ratio 3:2 out.jpg.
qub*_*dup 19
如果你最终的目标是具有一定的分辨率(例如1920x1080),那么使用-geometry,circumflex/hat/roof/house符号(^)和-crop:
convert in.jpg -geometry 1920x1080^ -gravity center -crop 1920x1080+0+0 out.jpg
循环遍历多个jpg文件:
for i in *jpg
  do convert "$i" -geometry 1920x1080^ -gravity center -crop 1920x1080+0+0 out-"$i"
done
如果你想避免缩放,你必须计算Imagemagick之外的裁剪边的新长度.这涉及更多:
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更有用.更改1920x1080解决方案1中的出现次数或解决方案2中的aw/ ah变量,以获得所需的宽高比.
fmw*_*w42 13
Imagemagick的最新版本(自6.9.9-34开始)具有方面裁剪.所以你可以这样做:
输入:
convert barn.jpg -gravity center -crop 3:2 +repage barn_crop_3to2.png
输出为400x267 + 0 + 0.但请注意,需要+ repage才能删除400x299 + 0 + 16的虚拟画布,因为PNG输出支持虚拟画布.JPG输出不需要+ repage,因为它不支持虚拟画布.
您需要计算出所需的尺寸,然后进行裁剪。这是一个函数,给定图像的width和height加上所需的宽高比 和aspect_x,aspect_y将输出可与 Imagemagick 一起使用的裁剪字符串。
def aspect(width, height, aspect_x, aspect_y)
  old_ratio = width.to_f / height
  new_ratio = aspect_x.to_f / aspect_y
  return if old_ratio == new_ratio
  if new_ratio > old_ratio
    height = (width / new_ratio).to_i # same width, shorter height
  else
    width = (height * new_ratio).to_i # shorter width, same height
  end
  "#{width}x#{height}#" # the hash mark gives centre-gravity
end
我在使用 Dragonfly Gem 的应用程序中使用了与此类似的东西。
| 归档时间: | 
 | 
| 查看次数: | 8305 次 | 
| 最近记录: |