javascript - 在将图像发送到服务器之前使用/wo Direct Upload 和 Canvas/Compress.js 向 Rails Active Storage 应用程序添加压缩
问题描述
我已经使用过 Active Storage 和 Direct Uploads。我已经安装了 ActiveStorage 并创建了数据库,所以添加图像没有问题。我已将此添加到我的模型中:
class Project < ApplicationRecord
has_many_attached :images
end
并将表单字段放在视图中:
<%= f.file_field :images, accept:'image/*', class: "input-file" multiple %>
并将其添加到我的控制器中:
private
def project_params
params.require(:project).permit(:title, :content, images: [])
end
不确定这是否会节省我的数据(因为大多数照片可能会很大),但任何关于实施的建议都会很棒。我想使用base64获得类似canvas compress的东西(再次不确定这是否是最好的)并调整大小,转换为blob然后上传或像compress.js这样的javascript压缩(https://www.npmjs.com/package/compress .js)处理图像,以便在将它们发送到服务器之前在用户端进行压缩和调整大小,从而减少发送的数据量。
我在这里找到了这段代码,我不太确定或者如何集成这样的东西,因为 Javascript 不在我的驾驶室中。
function compressImage (base64) {
const canvas = document.createElement('canvas')
const img = document.createElement('img')
return new Promise((resolve, reject) => {
img.onload = function () {
let width = img.width
let height = img.height
const maxHeight = 200
const maxWidth = 200
if (width > height) {
if (width > maxWidth) {
height = Math.round((height *= maxWidth / width))
width = maxWidth
}
} else {
if (height > maxHeight) {
width = Math.round((width *= maxHeight / height))
height = maxHeight
}
}
canvas.width = width
canvas.height = height
const ctx = canvas.getContext('2d')
ctx.drawImage(img, 0, 0, width, height)
resolve(canvas.toDataURL('image/jpeg', 0.7))
}
img.onerror = function (err) {
reject(err)
}
img.src = base64
})
}
基本上我问的是一个两部分的问题。如果我的用户将上传许多照片(显示分辨率不必保持超高)将使用带有 base64 的画布压缩然后将图像作为 blob 返回是最好的用途,或者只是坚持直接上传(rails js)而不是为压缩图像而烦恼?第二部分是如果这是一个好主意,我将如何实施?许多网站已经在不需要保持原始照片大小的情况下这样做了。
解决方案
推荐阅读
- awesome-wm - 在最小化窗口之间循环,同时保留位置
- javascript - 简单的加法
- python - 如何将 JSON 文件数据插入到表中
- java - 将对象放入 JComboBox
- php - 未定义的属性:> 在 Laravel 上使用日期类型列时出现 stdClass 错误。我该如何解决?
- php - 为什么 php curl 不适用于应用程序/json 发布?
- c# - 如何序列化 Microsoft.SqlServer.Types?
- java - 无法配置 Ignite Web 会话集群
- sql - 在其他列的基础上合并值列而不使用多个左连接
- caching - 使用 StackExchange.Redis 进行删除操作的 Redis 键空间通知