ImageMagick如何将重力和范围仅应用于短图像

时间:2019-07-08 13:12:13

标签: ruby-on-rails imagemagick minimagick

我有一个网页,其中列出了应为600px x 600px(宽度和高度)的图像。因此,我使用imagemagick将所有大图像的尺寸调整为600x600,效果很好。

但是,当我调整某些图像的大小(以保持其长宽比)时,某些图像的大小将调整为小于600px的高度(例如600x450)。因此,我尝试通过使用像这样的imagemagick选项(重力,背景和范围)来填充所需的高度:

image.combine_options do |img|
    img.crop('1200x1200+0+0')
    img.resize '600x600'
    img.background 'white'
    img.extent '600x600'
    img.gravity 'center'
end

这给了我我想要这些图像(短图像)的需求。但是,居中的效果也将应用于其他图像(较大的图像)!有什么办法可以防止这种情况?

更新

只是为了向您展示我的意思,我组成了这个示例...如果不添加范围和重力,图像将从左上角开始

enter image description here

但是如果我添加范围和重力(中心),则图像将从中心开始,如下所示:

enter image description here

我只希望将在尺寸小于600x600的调整大小图像上产生的图像居中,但是在示例中,您甚至看到将尺寸调整为精确的600x600的图像都居中!那不是我想要的

解决方案:

我最终在ruby中使用 system 函数使用shell命令

system "convert #{image.path} -crop 1024x1024+0+0 -resize 600x600 -background white -gravity center -extent 600x600 output.png"

,效果很好!我不知道为什么minimagick无法正常工作,但是我只是从我的gemfile中删除了该gem,这也很好。

1 个答案:

答案 0 :(得分:0)

这是您在Imagemagick命令行中使用的命令,裁剪后正确重置了虚拟画布。

convert image -crop 1200x1200+0+0 +repage -resize 600x600 -background white -gravity center -extent 600x600 result

以下是两个带有大小调整参数的结果。看来您的命令正在使用与resize参数上设置的^标志等效的命令。

输入:

enter image description here

不带^标志的正确结果:(注释用白色填充)

convert wiki.png -crop 1200x1200+0+0 +repage -resize 600x600 -background white -gravity center -extent 600x600 result1.png


enter image description here

带有^标志的结果:(已裁剪注释)

convert wiki.png -crop 1200x1200+0+0 +repage -resize 600x600^ -background white -gravity center -extent 600x600 result2.png


enter image description here

上面是Unix语法。对于Windows,因为^是Windows中的转义字符,所以将^翻倍为^^。

也许您遇到的问题是minimagick而不是Imagemagick。您可以通过测试我的命令行进行检查。