图片压缩
Posted FromXTLeo
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了图片压缩相关的知识,希望对你有一定的参考价值。
如题
const compressImage = async (file, quality=.9) => {
// file 文件对象
// quailty 压缩比
let img = new Image(),
reader = new FileReader(),
canvas = document.createElement(\'canvas\'),
ctx = canvas.getContext(\'2d\')
reader.readAsDataURL(file)
reader.onload = function(e){
img.src = e.target.result
}
return new Promise((resolve, reject)=>{
img.onload = function(){
let _ = this,
w = _.width,
h = _.height,
scale = w / h,
anw = document.createAttribute(\'width\'),
anh = document.createAttribute(\'height\')
anw.nodeValue = w
anh.nodeValue = h
canvas.setAttribute(anw)
canvas.setAttribute(anh)
// 在canvas绘制前填充白色背景
ctx.rect(0, 0, w, h)
ctx.fillStyle = \'white\'
ctx.fill()
ctx.drawImage(_, 0, 0, w, h)
let src = canvas.toDataURL(\'image/jpeg\', quality) //quality 在 \'image/jpeg\' 时才起作用
// base64转file
let arr = src.split(\',\'),
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(8)
while(n--){
u8arr[n] = bstr.charCodeAt(n)
}
let newFile = new File([u8arr], file.name, { type: file.type })
console.log(\'压缩后的图片体积\',newFile.size/1024/1024)
resolve(newFile)
}
})
}
外面调用
const egFunc = async (file)=>{
const quality = .5
file = await compressImage(file, quality)
}
以上是关于图片压缩的主要内容,如果未能解决你的问题,请参考以下文章