最近公司开发业务里有个需求是对上传图片进行压缩限制大小。实现限制大小的时候,采用的是二分法。
// 图片压缩大小至40kb, device为二分法压缩次数
// 这里压缩次数由图片大小去控制,可以多尝试几个数,来达到最好的压缩效果
CompressorImage(file, size = 40, device = 10) {
return new Promise((resolve) => {
const reader = new FileReader() // 创建fileReader
const canvas = document.createElement('canvas')
const context = canvas.getContext('2d')
reader.onload = ({ target: { result: src } }) => {
const image = new Image() // 创建 img 元素
image.onload = async () => {
// 原始图片尺寸
const originWidth = image.width
const originHeight = image.height
// 设置最大尺寸
const maxWidth = 1000
const maxHeight = 800
// 设置目标尺寸
let targetWidth = originWidth
let targetHeight = originHeight
// 图片尺寸超过限制
if (originWidth > maxWidth || originHeight > maxHeight) {
if (originWidth / originHeight > maxWidth / maxHeight) {
// 更宽 按照宽度限定尺寸
targetWidth = maxWidth
targetHeight = Math.round(maxWidth * (originHeight / originWidth))
} else {
// 更高 按照高度限定尺寸
targetHeight = maxHeight
targetWidth = Math.round(maxHeight * (originWidth / originHeight))
}
}
// canvas对图片进行缩放
canvas.width = targetWidth
canvas.height = targetHeight
// 清除画布
if (context) context.clearRect(0, 0, targetWidth, targetHeight)
// 将图片划到canvas上
if (context) context.drawImage(image, 0, 0, targetWidth, targetHeight)
let canvasURL, miniFile
let L = true
let quality = 0
const detail = []
let start = Date.now()
for (let i = 1; i <= device; i++) {
canvasURL = canvas.toDataURL('image/jpeg', L ? (quality += 1 / 2 ** i) : (quality -= 1 / 2 ** i))
const buffer = atob(canvasURL.split(',')[1])
let length = buffer.length
const bufferArray = new Uint8Array(new ArrayBuffer(length))
while (length--) {
bufferArray[length] = buffer.charCodeAt(length)
}
miniFile = new File([bufferArray], file.name, { type: 'image/jpeg' })
miniFile.size / 1024 > size ? (L = false) : (L = true)
detail.push({
quality,
size: miniFile.size,
kb: Number((miniFile.size / 1024).toFixed(2)),
time: Date.now() - start,
})
start = Date.now()
}
const targetFile = this.baseToBlob(canvasURL, file.name)
resolve({
targetFile,
})
}
image.src = src
}
reader.readAsDataURL(file)
})
},
baseToBlob(dataurl, fileName) {
var arr = dataurl.split(',')
var mime = arr[0].match(/:(.*?);/)[1]
var bstr = atob(arr[1])
var n = bstr.length
var u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
}
const theBlob = new Blob([u8arr], { type: mime })
let files = new File([theBlob], fileName, { type: 'image/jpeg' })
theBlob.lastModifiedDate = new Date()
theBlob.name = fileName
return files
},