如何在使用 ActiveStorage 上传到云之前压缩图像

Joe*_*ina 5 ruby-on-rails rails-activestorage

为了节省云中的空间,您将如何使用 activestorage 调整和压缩图像的大小?

iGi*_*ian 2

我在本地存储的开发中测试了下面的代码,它可以工作,但无论如何都会出现一些问题,我将在接下来解释。

在创建时,这似乎工作得很好,即使我认为应该有一种更干净的方法来做到这一点。

class User < ApplicationRecord
  has_one_attached :avatar

  before_save :resize_avatar_image

  def resize_avatar_image
    filename = avatar.filename.to_s
    puts attachment_path = "#{Dir.tmpdir}/#{avatar.filename}"
    File.open(attachment_path, 'wb') do |file|
       file.write(avatar.download)
       file.close
    end
    image = MiniMagick::Image.open(attachment_path)
    # if image.width ...
    image.resize "40x40"
    image.write attachment_path
    avatar.attach(io: File.open(attachment_path), filename: filename, content_type: "image/jpg")
  end

end
Run Code Online (Sandbox Code Playgroud)

我遇到的问题有人可以解决

  1. 如果不下载到临时文件以便使用 MiniMagick 处理它,我无法即时应用变体
  2. 更新(编辑)时,由于 purge 和 purge_later 方法出现错误,过程很慢:[ActiveJob] [ActiveStorage::PurgeJob] [d6a930ee-32cd-45a7-bfb5-72929d79f9bb] Error performing ActiveStorage::PurgeJob (Job ID: d6a930ee-32cd-45a7-bfb5-72929d79f9bb) from Async(default) in 0.33ms: ArgumentError (wrong number of arguments (given 0, expected 1));我找不到解决方法。检查旧的 blob 是否已删除。
  3. 第2点提到的问题似乎与方法有关.attach
  4. 我只测试了*.jpg并且*.png
  5. 未在生产中或远程存储中进行测试