我在 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
用户.rb
class User < ApplicationRecord
include ImageUploader::Attachment(:image)
before_save :image_resize
def image_resize
self.image_derivatives!
end
end
我在阅读 official documentation 时实现了它, 但这在两个方面是不可取的。
- 需要模型代码中的触发器。只用
image_uploader.rb
可以完成吗? - 访问使用此代码生成的图像需要“调整大小”前缀(例如
@user.image(:resized).url
),原始图像也将保留在存储中。我想处理原始图像本身。
有没有办法一边上传一边解决这两个问题?
最佳答案
您可以添加以下补丁,这将触发派生创建,作为将缓存文件提升为永久存储的一部分:
# put this in your initializer class Shrine::Attacher def promote(*) create_derivatives super end end
您可以只覆盖检索附加文件的模型方法以返回调整后的版本。您可以使用
included
插件对使用此 uploader 的所有模型执行此操作:class ImageUploader < Shrine # ... plugin :included do |name| define_method(name) { super(:resized) } end end
关于第二个问题:它仍然会保留原始文件在存储中,但默认返回调整后的版本。通常最好在 View 装饰器中执行此操作。
您总是希望将原始文件保留在存储器中,因为您永远不知道何时需要重新处理它。您可能会发现当前的调整大小逻辑不适合某些文件类型和大小,在这种情况下,您需要为以前的附件重新生成调整大小的版本。如果您不再拥有原始文件,您将无法执行此操作。
关于ruby-on-rails - 如何在 Shrine 中调整原始图像本身的大小上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59021782/