如何在 Shrine 中调整原始图像本身的大小上传
How to upload while resizing the original image itself in Shrine
我在 Rails 应用程序的 Ruby 中使用 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
我在阅读 official documentation 时实现了它,但这在两个方面是不可取的。
- 需要模型代码中的触发器。只用
image_uploader.rb
就可以完成吗?
- 访问使用此代码生成的图像需要一个 "resized" 前缀(例如
@user.image(:resized).url
),原始图像也将保留在存储中。我想自己处理 原始图像。
有没有办法一边上传一边解决这两个问题?
您可以添加以下补丁,这将触发派生创建作为将缓存文件提升为永久存储的一部分:
# put this in your initializer
class Shrine::Attacher
def promote(*)
create_derivatives
super
end
end
您可以将检索附件的模型方法重写为 return 调整后的版本。您可以使用 included
插件对使用此上传器的所有模型执行此操作:
class ImageUploader < Shrine
# ...
plugin :included do |name|
define_method(name) { super(:resized) }
end
end
关于第二个问题:它仍然会在存储中保留原始文件,但默认情况下只是 return 调整后的版本。通常最好在视图装饰器中执行此操作。
您总是希望将原始文件保留在存储中,因为您永远不知道何时需要重新处理它。您可能会发现当前的调整大小逻辑不适合某些文件类型和大小,在这种情况下,您需要为以前的附件重新生成调整大小的版本。如果您不再拥有原始文件,您将无法执行此操作。
我在 Rails 应用程序的 Ruby 中使用 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
我在阅读 official documentation 时实现了它,但这在两个方面是不可取的。
- 需要模型代码中的触发器。只用
image_uploader.rb
就可以完成吗? - 访问使用此代码生成的图像需要一个 "resized" 前缀(例如
@user.image(:resized).url
),原始图像也将保留在存储中。我想自己处理 原始图像。
有没有办法一边上传一边解决这两个问题?
您可以添加以下补丁,这将触发派生创建作为将缓存文件提升为永久存储的一部分:
# put this in your initializer class Shrine::Attacher def promote(*) create_derivatives super end end
您可以将检索附件的模型方法重写为 return 调整后的版本。您可以使用
included
插件对使用此上传器的所有模型执行此操作:class ImageUploader < Shrine # ... plugin :included do |name| define_method(name) { super(:resized) } end end
关于第二个问题:它仍然会在存储中保留原始文件,但默认情况下只是 return 调整后的版本。通常最好在视图装饰器中执行此操作。
您总是希望将原始文件保留在存储中,因为您永远不知道何时需要重新处理它。您可能会发现当前的调整大小逻辑不适合某些文件类型和大小,在这种情况下,您需要为以前的附件重新生成调整大小的版本。如果您不再拥有原始文件,您将无法执行此操作。