简而言之:
img.crop("#{size}#{offset}") # Doesn't return an image...
img # ...so you'll need to call it yourself
这是一个更好的解释为什么会发生这种情况,而不是剪切/粘贴样式的解决方案。
RMagick 和 MiniMagick 不可互换。RMagick 有一个非常像 Ruby 的 DSL,因此采用了带有多个参数的方法:
rmagick_image.crop(x_offset, y_offset, width, height) # Returns an image object
rmagick_image.crop!(x_offset, y_offset, width, height) # Edits object in place
MiniMagick 而是通过迭代与MOGRIFY_COMMANDS
ImageMagickmogrify
文档中指定的许多以破折号为前缀的选项匹配的列表来动态生成方法。这些方法中的每一个都直接将它们的参数传递给mogrify
并且没有一个返回图像对象:
minimagick_image.crop('100x200') # Translates to `mogrify -crop 100x200 image.ext`
minimagick_image.polaroid('12') # Executes `mogrify -polaroid 12 image.ext`
在实物上,RMagick 有crop!
,而 MiniMagick 没有。
根据 ImageMagick 文档,mogrify -crop
需要一个参数geometry
。这里解释了这个geometry
论点。您会注意到所有这些参数都是字符串,因此您可以使用or代替。它不是很像 Ruby,但这就是 MiniMagick 如此轻量级的部分原因。crop(100,200)
crop('100x200')
crop('100%)
有了这些知识,我们就可以推断出如何使用 MiniMagick 进行裁剪。可以将几何图形mogrify -crop
作为字符串width
x height
++,所以我们只需要构建一个类似的字符串。xoffset
yoffset
给定w
, h
, x
, 并且y
您可以使用以下您认为最易读的任何一个:
# Concatenating plus signs with plus signs is atrociously confusing.
# Recommended only if you want to drive your future self insane.
mogrify_arg = w + 'x' + h + '+' + x + '+' + y
# Readable but inefficient
mogrify_arg = [ w, 'x', h, '+', x, '+', y ].join('')
# Questionable readability
mogrify_arg = "#{w}x#{h}+#{x}+#{y}"
# Slick, performant, but potentially risky: `<<` modifies the receiving object in place
# `w` is actually changing here to "WxH+X+Y"...
mogrify_arg = w << 'x' << h << '+' << x << '+' << y
# A lovely, self-documenting version
size = w << 'x' << h
offset = '+' << x '+' << y
mogrify_arg = "#{size}#{offset}"
这是一个完整的例子:
def crop
if model.crop_x.present?
resize_to_limit(700, 700)
manipulate! do |img|
x = model.crop_x
y = model.crop_y
w = model.crop_w
h = model.crop_h
size = w << 'x' << h
offset = '+' << x << '+' << y
img.crop("#{size}#{offset}") # Doesn't return an image...
img # ...so you'll need to call it yourself
end
end
end