1、定义--压缩动态图片方法
export const gifCompress = (file, url, max, min, times) => {
if (window.FileReader) {
let colors = 255
let count = 0
const fr = new FileReader()
fr.readAsArrayBuffer(file)
return new Promise((resolve) => {
fr.onload = async(e) => {
const fn = async() => {
count++
// eslint-disable-next-line no-undef
const result = await gifmin(fr.result, colors) // 二进制文件流
const blob = await new Blob([result], { // 转换成Blob对象
type: 'application/octet-stream'
})
if (blob.size > max && count < times) {
// eslint-disable-next-line require-atomic-updates
colors = Math.floor(colors / 2)
fn()
} else {
resolve({ blob, url })
}
}
fn()
}
})
} else {
imgCompress(file, url)
}
}
2、定义--压缩静态图片方法
export const staticCompress = (file, url, max, min, times) => {
const img = new Image()
img.src = url
return new Promise((resolve) => {
img.onload = async() => {
const canvas = document.createElement('canvas')
const { width: originWidth, height: originHeight } = img
canvas.width = originWidth
canvas.height = originHeight
const ctx = canvas.getContext('2d')
ctx.drawImage(img, 0, 0, originWidth, originHeight)
let blob = await new Promise((resolve1) => {
canvas.toBlob((res) => {
resolve1(res)
}, 'image/jpeg')
})
if (blob.size > max) {
const resp = await compress(canvas, max, min, times)
blob = resp.blob
}
resolve({ blob, url })
}
})
}
3、图片压缩
export const imgCompress = async(file, max = 200 * 1024, min = 10 * 1024, times = 3) => {
const URL = window.URL || window.webkitURL
const url = URL.createObjectURL(file)
if (file.type === 'image/gif') {
return gifCompress(file, url, max, min, times)
} else {
return staticCompress(file, url, max, min, times)
}
}