我目前正在使用 Paperclip 上传图像并自动生成缩略图。现在我还想添加第二种样式,它使用上传图像中最左边的像素列生成一个像素宽的图像(它也应该与原始图像具有相同的高度)。我将通过 CSS 使用一个像素宽的图像作为重复背景。
是否可以使用 Paperclip 的默认缩略图处理器生成该背景图像,或者我需要创建自己的自定义处理器?我已经尝试创建一个子类化的自定义处理器Paperclip::Processor
,但我不明白如何Paperclip.run
正确使用该方法。现在我正在尝试Paperclip::Thumbnail
基于 Ryan Bate 的 Railcast进行子类化: http ://railscasts.com/episodes/182-cropping-images ,但这会引发此错误:
NoMethodError (You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.[]):
app/controllers/images_controller.rb:11:in `create'
images_controller.rb 的第 11 行:
@image = @review.images.build(params[:image])
如果我不尝试使用 Autobackground 自定义处理器,images_controller.rb 的第 11 行工作正常,因此错误必须是处理器中的代码。
到目前为止,这是我的代码:
#/app/models/image.rb
class Image < ActiveRecord::Base
belongs_to :review
has_attached_file :image, :styles => {
:thumb => "32x32#",
:auto_bg => { :processors => [:autobackground] }
}
end
#/lib/paperclip_processors/Autobackground.rb
module Paperclip
class Autobackground < Thumbnail
def transformation_command
if crop_command
crop_command + super.sub(/ -crop \S+/, '')
else
super
end
end
def crop_command
target = @attachment.instance
if target.cropping?
" -crop '1x#{target.height}+0+0'"
end
end
end
end