[英]How to crop image manually with paperclip?
I'm building a website with Rails 4.2 and Mongoid. 我正在用Rails 4.2和Mongoid建立一个网站。 I'm using mongoid-paperclip , and I'm trying to crop an image down to a square while preserving the dimensions of the short side (so the image will fill the full square).
我正在使用mongoid-paperclip ,并且尝试将图像裁剪为正方形,同时保留短边的尺寸(以便图像将填满整个正方形)。 Here's my custom processor:
这是我的自定义处理器:
module Paperclip
class Cropper < Thumbnail
def initialize(file, options = {}, attachment = nil)
super
@preserved_size = [@current_geometry.width, @current_geometry.height].min
@current_geometry.width = @preserved_size
@current_geometry.height = @preserved_size
end
def target
@attachment.instance
end
def transformation_command
if crop_command
crop_command + super.join(' ').sub(/ -crop \S+/, '').split(' ')
else
super
end
end
def crop_command
["-crop", "#{@preserved_size}x#{@preserved_size}+#{@preserved_size}+#{@preserved_size}"]
end
end
end
And the model that it's attached to looks has this line: 它所连接的模型看起来像这样:
has_mongoid_attached_file :image, styles: {square: {processors: [:cropper]}}
But it doesn't seem to work. 但这似乎不起作用。 A version of the image named 'square' is saved, but it's identical to the original.
保存了名为“ square”的图像版本,但与原始版本相同。 How can I get this to work?
我该如何工作?
I was able to fix this without using a paperclip processor. 我无需使用回形针处理器即可解决此问题。 In my model, I specified the
styles
for the image using a lambda: 在我的模型中,我使用lambda指定了图像的
styles
:
has_mongoid_attached_file :image, styles: lambda {|a|
tmp = a.queued_for_write[:original]
return {} if tmp.nil?
geometry = Paperclip::Geometry.from_file(tmp)
preserved_size = [geometry.width.to_i, geometry.height.to_i].min
{square: "#{preserved_size}x#{preserved_size}#"}
}
Note that the #
at the end of the dimensions ensured that the cropped image was always the specified dimensions, rather than just scaling down the image. 请注意,尺寸末尾的
#
确保裁剪后的图像始终是指定的尺寸,而不仅仅是缩小图像。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.