Chen Yangjian's Blog

Carpe diem - Seize the day

RMagick、MiniMagick、ImageMagick、GraphicsMagick 傻傻分不清楚

| Comments

四兄弟都是 Magick 字辈的,要分清楚其实也简单。ImageMagickGraphicsMagick 是名副其实的两兄弟,都是开源的图片处理工具,具有丰富的执行参数,艺术效果等等。后者是前者的分支,从 2002 年时的 5.5.2 版本分出来,专注软件与编程接口的稳定性。

而 RMagick 与 MiniMagick 也算是两兄弟,后者比前者优势在更稳定,不容易内存泄露(That’s what they say…)。哥俩都是 Ruby Gem,是对 ImageMagick 的命令行选项的封装。中午查文档的时候瞥了一眼 MiniMagick 的些许代码,也是用的 method_missing 来搞。例如:

foo.rb
1
2
3
4

img = MiniMagick::Image.read(blob)
img.resize '800x800'
# method_missing thrown, resize wrapped as an option of `convert` command.

所以,基本上对着 ImageMagick 的文档用就是了。

然后再提一个经常用到的实践,在 CarrierWave 的封装里头也很常见的,resize_to_fit 与 resize_to_limit,以及其他一些需求,例如我今天要做的,把图片宽度限制在 800 以内,高度不限。这种需求都可以通过 -resize 参数统统搞定。在文档里头我们看到,它说接收一个 geometry 格式的参数。那这个 geometry 参数长啥样嘞?

scale%  Height and width both scaled by specified percentage.
scale-x%xscale-y%   Height and width individually scaled by specified percentages. (Only one % symbol needed.)
width   Width given, height automagically selected to preserve aspect ratio.
xheight Height given, width automagically selected to preserve aspect ratio.
widthxheight    Maximum values of height and width given, aspect ratio preserved.
widthxheight^   Minimum values of width and height given, aspect ratio preserved.
widthxheight!   Width and height emphatically given, original aspect ratio ignored.
widthxheight>   Change as per widthxheight but only if an image dimension exceeds a specified dimension.
widthxheight<   Change dimensions only if both image dimensions exceed specified dimensions.
area@   Resize image to have specified area in pixels. Aspect ratio is preserved.

这货定义的真是太精彩了,言简意赅,上面的那些需求都可以分别满足:

-resize 80x80
-resize 80x80>
-resize 80
-reszie 80x800< # 如果刷屏金箍棒出现

不过话说回来,在可读性与简洁之间,确实很难做好平衡呢。

Comments