如何使用ActiveStorage在上传到云之前压缩图像
为了节省云中的空间,您将如何使用activestorage调整图像预上载的大小和压缩?
我在本地存储的开发中测试了下面的代码并且它可以工作,但无论如何都会给出一些我将在下面解释的问题。
在创建这似乎工作正常,即使我认为应该有一个更清洁的方法这样做。
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
我遇到的问题,有人可以克服
- 我无法在不下载到临时文件的情况下动态应用变体,以便使用MiniMagick进行处理
- 更新(编辑)时,由于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是否已删除。 - 第2点提到的问题似乎与
.attach
方法有关; - 我只测试了
*.jpg
和*.png
- 未在生产和远程存储中测试过