js图片压缩
compressImg (base64, scale, callback) {
console.log(`执行缩放程序,scale=${scale}`);
const img = new Image()
img.src = base64
img.onload = function () {
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')
canvas.setAttribute('width', this.width)
canvas.setAttribute('height', this.height)
ctx.clearRect(0, 0, canvas.width, canvas.height)
ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
let base64 = canvas.toDataURL('image/jpeg')
while (base64.length > 1024 * 1024 * 4) {
scale -= 0.01
base64 = canvas.toDataURL('image/jpeg', scale)
}
const arr = base64.split(',')
const mime = arr[0].match(/:(.*?);/)[1]
const bytes = atob(arr[1])
const bytesLength = bytes.length
const u8arr = new Uint8Array(bytesLength)
for (let i = 0; i < bytes.length; i++) {
u8arr[i] = bytes.charCodeAt(i)
}
const blob = new Blob([u8arr], { type: mime })
callback(blob, base64,canvas.width,canvas.height)
}
},