最近在做一个政务类的移动端H5项目,用户体量达百万级别,有一个模块中有上传图片反馈的功能,由于各个手机产商拍照的像素值的都不一样,后台去浏览这个图片的时候就出现大小不一的情况,另外有些图片并不需要上传原始尺寸,再加上大流量的情况下就造成了服务器资源不必要的浪费,于是就有了将上传图片压缩的需求
图像压缩原理
图像压缩有两种方式,目前写的方法是两者都支持且能够共同处理
1.图像尺寸裁剪,由大变小
2.尺寸不变,图片质量缩减
引用代码
if (!HTMLCanvasElement.prototype.toBlob) {
Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {
value: function(callback, type, quality) {
var canvas = this
setTimeout(() => {
var binStr = atob(canvas.toDataURL(type, quality).split(',')[1])
var len = binStr.length
var arr = new Uint8Array(len)
for (var i = 0; i < len; i++) {
arr[i] = binStr.charCodeAt(i)
}
callback(new Blob([arr], { type: type || 'image/png' }))
})
}
})
}
const compressionImage = ({ content, maxWidth = 2000, maxHeight = 2000, quality = 1 }) => {
return new Promise(resolve => {
const set = (fileContent, fileType, fileName) => {
const canvasDOM = document.createElement('canvas')
const canvasContext = canvasDOM.getContext('2d')
const img = new Image()
img.src = fileContent
img.onload = () => {
let targetWidth
let targetHeight
if (img.width > maxWidth && img.height > maxHeight) {
const rate = Math.min(maxWidth / img.width, maxHeight / img.height)
targetWidth = img.width * rate
targetHeight = img.height * rate
} else if (img.width > maxWidth) {
targetWidth = maxWidth
targetHeight = (maxWidth / img.width) * img.height
} else if (img.height > maxHeight) {
targetHeight = maxHeight
targetWidth = (maxHeight / img.height) * img.width
} else {
targetWidth = img.width
targetHeight = img.height
}
canvasDOM.width = targetWidth
canvasDOM.height = targetHeight
canvasContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, targetWidth, targetHeight)
const url = canvasDOM.toDataURL(fileType, quality)
const callback = blob => {
resolve({ url, blob })
}
canvasDOM.toBlob(callback, fileType, quality)
}
}
if (content instanceof File) {
const fileReader = new FileReader()
fileReader.readAsDataURL(content)
fileReader.onload = e => {
set(e.target.result, content.type, content.name)
}
} else if (typeof content === 'string') {
const fileType =
content.includes('data:image/png;base64') ? 'image/png'
: content.includes('data:image/gif;base64') ? 'image/gif' : 'image/jpeg'
set(content, fileType, `file-${+new Date()}`)
}
})
}
调用方式
const { url, blob } = await compressionImage({
content: 'base64', //图像base64或file文件
maxWidth: 1000, //最大宽度
maxHeight: 600, //最大高度
quality: 0.7 //图像质量,1为100%,建议选值0.95以下,1输出后的图像较大
})
console.log('压缩后的base64内容', url)
console.log('压缩后的blob文件', blob)
结果查看
对图片的尺寸和质量都进行了压缩,原始图像306b,压缩后的图像86kb