【问题标题】:How to compress images before uploading to the cloud using ActiveStorage如何在使用 ActiveStorage 上传到云之前压缩图像
【发布时间】:2018-06-13 18:45:30
【问题描述】:

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

【问题讨论】:

  • 从未尝试过,但我会尝试的。我想您需要启用 mini_magick gem 并在回调中使用 imagemagick,也许是:image.variant(resize: "500x500")。我发现这篇博文是一个有用的资源:@​​987654321@
  • iGian 的解决方案对您有用吗?

标签: ruby-on-rails rails-activestorage


【解决方案1】:

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

在创建时这似乎工作正常,即使我认为应该有更清洁的方法。

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

我遇到的有人可以克服的问题

  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. 未经生产测试,也不用于远程存储

【讨论】:

  • 这只是调整图像大小吧?如何压缩图像以节省空间,例如上传到 facebook 或 whatsapp?
猜你喜欢
  • 1970-01-01
  • 2021-01-03
  • 2023-03-19
  • 1970-01-01
  • 2019-02-10
  • 1970-01-01
  • 1970-01-01
  • 2018-02-17
相关资源
最近更新 更多