本文介绍了如何在使用 ActiveStorage 上传到云之前压缩图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为了节省云中的空间,您将如何使用 activestorage 调整和压缩图像的大小?
To save space in the cloud how would you go about resizing and compressing an image preupload using activestorage?
推荐答案
我在本地存储的开发中测试了下面的这段代码,它可以工作,但无论如何都会出现一些问题,我将在接下来解释.
I tested this code below in development on local storage and it works, but anyway gives some problems that I will explain next.
在创建时这似乎工作正常,即使我认为应该有一种更简洁的方法来做到这一点.
On create this seems to work fine, even if I suppose there should be a cleaner way to do so.
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] 执行 ActiveStorage::PurgeJob 时出错(作业 ID:d6a930ee-32cd-45a7-bfb5-72929d79f9bb)从异步(默认)在 0.33 毫秒内:ArgumentError(参数数量错误(给定 0,预期为 1))
;我找不到解决方法.检查旧 blob 是否已删除. - 第2点提到的问题似乎与
.attach
方法有关; - 我只测试了
*.jpg
和*.png
- 未在生产中或远程存储中进行测试
- I was not able to apply variations on the fly without downloading to a temp file in order to process it with MiniMagick
- When updating (edit) the process is slow because of errors with purge and purge_later methods:
[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))
; I could not find a workaround. Check if the old blob was deleted. - The problem mentioned at point 2 seems to be related with
.attach
method; - I tested only
*.jpg
and*.png
- Not tested in production nor for remote storage
这篇关于如何在使用 ActiveStorage 上传到云之前压缩图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!