[英]How to upload while resizing the original image itself in Shrine
我在 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
用户名
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
至于第二个问题:它仍然会在存储中保留原始文件,但默认情况下只是返回调整后的版本。 通常最好在视图装饰器中执行此操作。
您总是希望将原始文件保留在存储中,因为您永远不知道何时需要重新处理它。 您可能会发现当前的调整大小逻辑对于某些文件类型和大小并不理想,在这种情况下,您需要为以前的附件重新生成调整大小的版本。 如果您不再拥有原始文件,您将无法做到这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.