我已经来过这一段时间了。至少从理论上讲,使用此RailsCast我已经能够对其进行修改以与CarrierWave一起使用。我试图允许用户裁剪其个人资料照片,然后使用CarrierWave将其上传到S3。到目前为止,这是可行的:
用户上传图片以及其他个人资料信息
他们被成功带到裁剪页面,可以在其中裁剪照片-上传照片并成功捕获原始图像尺寸
单击“裁剪”以保存图像不会触发任何错误(模型保存很好),但据我所知,实际上也不会裁剪或重新创建版本。
所以,这是我得到的代码。这是模型:
attr_accessor :crop_x, :crop_y, :crop_w, :crop_h, :original_width, :original_height
attr_accessible :avatar, :remove_avatar
after_update :reprocess_avatar, :if => :cropping?
mount_uploader :avatar, ProfileBaseUploader
def cropping?
!crop_x.blank? && !crop_y.blank? && !crop_w.blank? && !crop_h.blank?
end
private
def reprocess_avatar
avatar.process!
avatar.recreate_versions!
end
漂亮的样板-作物视图中分配了crop_x等属性。我已经确认这些消息已正确传递并正确分配,并且已调用reprocess_avatar方法。
这是我的上传者代码:
include CarrierWave::MiniMagick
include CarrierWaveDirect::Uploader
storage :fog
require 'guid'
process :cropper
process :store_best_geometry
version :tiny_thumb do
process :resize_to_limit => [50, 50]
end
version :thumb do
process :resize_to_limit => [200, 200]
end
version :large do
process :resize_to_fit => [500, 500]
end
def extension_white_list
%w(jpg jpeg gif png)
end
def filename
@name ||= "#{secure_token}.#{file.extension}" if original_filename.present?
end
def store_best_geometry
manipulate! do |img|
if model
model.original_width = img['width']
model.original_height = img['height']
end
img = yield(img) if block_given?
img
end
end
def cropper
return unless model.cropping?
manipulate! do |img|
img = img.crop("#{model.crop_x}x#{model.crop_y}+#{model.crop_w}+#{model.crop_h}")
img
end
end
protected
def secure_token
var = :"@#{mounted_as}_secure_token"
model.instance_variable_get(var) or model.instance_variable_set(var, Guid.new)
end
我觉得那个过程!和recreate_versions!方法根本无法正常运行,但是我不知道为什么。我没有可以提供的任何错误(如果有人知道如何生成一个错误,我会很乐意这样做)。我知道store_best_geometry方法效果很好。播种者不能说同样的话。
有任何想法吗?
最佳答案
就像一次严重的飞机失事一样,我做错了很多事情。
首先,我提出了以错误的顺序种植作物的论点。在我的问题中,您会注意到我有:
img.crop('[x offset]x[y offset]+[width]+[height]')
正确的顺序是:
img.crop('[width]x[height]+[x offset]+[y offset]')
所以这是问题之一。尝试以错误的顺序进行操作会引发错误(将其拖入控制台以找到它),因为该几何无效。
下一个问题:使用我的裁剪器方法中断收益链,并返回STRING而不是IMAGE。结果是crop方法返回一个字符串。看一下原始的裁剪方法:
def cropper
return unless model.cropping?
manipulate! do |img|
img = img.crop("#{model.crop_x}x#{model.crop_y}+#{model.crop_w}+#{model.crop_h}")
img
end
end
糟糕!最后返回的是一个字符串。事实证明,正确的方法是直接在图像上调用方法:
def cropper
return unless model.cropping?
manipulate! do |img|
img.crop("#{model.crop_w}x#{model.crop_h}+#{model.crop_x}+#{model.crop_y}")
img = yield(img) if block_given?
img
end
end
我做错的最后一件事-这是一个完全的业余时间错误-没有使某些关键属性可访问。用我的无限智慧,我假设attr_accessor将使属性可访问。不。我必须修改模型以使crop_x,crop_y,crop_w和crop_h参数可访问。
attr_accessor :crop_x, :crop_y, :crop_w, :crop_h, :original_width, :original_height
attr_accessible :avatar, :remove_avatar, :crop_x, :crop_y, :crop_w, :crop_h
after_update :reprocess_avatar, :if => :cropping?
最后一点,不是很重要,但很容易知道。我不需要致电程序!作为recreate_versions!为我做到了。
希望这可以帮助至少一个人。
关于ruby-on-rails - 使用CarrierWave和MiniMagick将Rails裁剪并上传到S3,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10791554/