问题描述
我已经使用过 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 获得类似画布压缩的东西(再次不确定这是否最好)并调整大小,转换为 blob 然后上传或像 compress.js (https://www.npmjs.com/package/compress.js) 这样的 javascript 压缩处理图像,以便他们在发送到服务器之前在用户端进行压缩和大小调整,从而减少发送的数据量。
我在这里找到了这段代码,我不太确定或者如何集成这样的东西,因为 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,width,height)
resolve(canvas.toDataURL('image/jpeg',0.7))
}
img.onerror = function (err) {
reject(err)
}
img.src = base64
})
}
基本上我在问一个由两部分组成的问题。如果我的用户将上传许多照片(显示分辨率不需要保持超高)将使用带有 base64 的画布压缩然后将图像作为 blob 返回是最好的用途,或者只是坚持直接上传(rails js)而不是麻烦压缩图像?第二部分是如果这是一个好主意,我将如何实施?许多网站已经这样做了,而无需保持原始照片大小。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)