我在Ruby on Rails应用程序中使用Shrine来创建调整大小并将图像上传到存储的过程。
我当前的代码是:
image_uploader.rb
require "image_processing/mini_magick"
class ImageUploader < Shrine
plugin :derivatives
Attacher.derivatives_processor do |original|
magick = ImageProcessing::MiniMagick.source(original)
{
resized: magick.resize_to_limit!(120, 120)
}
end
end
user.rb
class User < ApplicationRecord
include ImageUploader::Attachment(:image)
before_save :image_resize
def image_resize
self.image_derivatives!
end
end
我在阅读官方文档时实现了它,但这在两种方式中是不可取的。
image_uploader.rb
吗?@user.image(:resized).url
),并且原始图像也将保留在存储中。我想处理原始图像本身。解决这两个问题时,是否可以上传?
您可以添加以下补丁,该补丁将触发派生创建,作为将缓存文件提升为永久存储的一部分:
# put this in your initializer
class Shrine::Attacher
def promote(*)
create_derivatives
super
end
end
您可以仅覆盖检索附件的模型方法以返回调整后的版本。您可以使用included
此上传器使用该插件对所有模型执行此操作:
class ImageUploader < Shrine
# ...
plugin :included do |name|
define_method(name) { super(:resized) }
end
end
至于第二个问题:它将仍然将原始文件保留在存储中,但是默认情况下,只返回调整大小的版本即可。通常最好在视图装饰器中执行此操作。
您始终希望将原始文件保留在存储中,因为您不知道何时需要重新处理它。可能会发现您当前的调整大小逻辑对于某些文件类型和大小而言并不理想,在这种情况下,您需要为先前的附件重新生成调整大小的版本。如果您再也没有原始文件,那么您将无法执行此操作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句