ruby-on-rails - 如何在 Shrine 中调整原始图像本身的大小上传

标签 ruby-on-rails ruby image-processing imagemagick 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

用户.rb

class User < ApplicationRecord
  include ImageUploader::Attachment(:image)
  before_save :image_resize

  def image_resize
    self.image_derivatives!
  end
end

我在阅读 official documentation 时实现了它, 但这在两个方面是不可取的。

  1. 需要模型代码中的触发器。只用image_uploader.rb可以完成吗?
  2. 访问使用此代码生成的图像需要“调整大小”前缀(例如 @user.image(:resized).url),原始图像也将保留在存储中。我想处理原始图像本身。

有没有办法一边上传一边解决这两个问题?

最佳答案

  1. 您可以添加以下补丁,这将触发派生创建,作为将缓存文件提升为永久存储的一部分:

    # put this in your initializer
    class Shrine::Attacher
      def promote(*)
        create_derivatives
        super
      end
    end
    
  2. 您可以只覆盖检索附加文件的模型方法以返回调整后的版本。您可以使用 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/

相关文章:

c++ - 如何将 char* 缓冲区转换为 unsigned char 缓冲区

java - 写灰度图出错

javascript - 当自动完成为 params 时返回 nil

javascript - Rails Assets 管道 - 自定义 js 文件

ruby-on-rails - Rails 连接表

ruby - 在 ubuntu 11.10 上运行

python - OpenCV2中connectedComponents的统计信息

mysql - 创建rails SUM查询对象

ruby-on-rails - 如何强制执行 BigDecimal 的有效位数

ruby - 为什么 Ruby/[[ :punct:]]/miss some punctuation characters?