/**
* 图片压缩
* @param {Object | Array} file 是对象或由这个对象组成的数组,这个对象的file元素是file文件,其他属性可以是一些status,message等状态属性
* @param {Function} callback 回调函数,压缩之后的内容通过回调函数返回
* 例: imgCompress(file, function(newFile) {})
*/
function imgCompress(file, callback) {
if (Array.isArray(file)) {
let tempArr = []
file.forEach((item, index) => {
singleCompress(item, function (newFile) {
tempArr.push(newFile)
if (file.length == index + 1) callback(tempArr)
})
})
} else {
singleCompress(file, function (newFile) {
callback(newFile)
})
}
}
// 单个图片压缩
function singleCompress(files, callback) {
let file = files
const img = new Image()
img.src = file.content
setTimeout(() => {
const { width: originWidth, height: originHeight } = img
// 最大尺寸限制
const maxWidth = 1000, maxHeight = 1000
// 需要压缩的目标尺寸
let targetWidth = originWidth, targetHeight = originHeight
// 等比例计算超过最大限制时缩放后的图片尺寸
if (originWidth > maxWidth || originHeight > maxHeight) {
if (originWidth / originHeight > 1) {
// 宽图片
targetWidth = maxWidth
targetHeight = Math.round(maxWidth * (originHeight / originWidth))
} else {
// 高图片
targetHeight = maxHeight
targetWidth = Math.round(maxHeight * (originWidth / originHeight))
}
}
// 创建画布
const canvas = document.createElement('canvas')
const context = canvas.getContext('2d')
// 设置宽高度为等同于要压缩图片的尺寸
canvas.width = targetWidth
canvas.height = targetHeight
context.clearRect(0, 0, targetWidth, targetHeight)
//将img绘制到画布上
context.drawImage(img, 0, 0, targetWidth, targetHeight)
canvas.toBlob(function (blob) {
let newFile = new File([blob], file.file.name, { type: file.file.type || 'image/png' })
file.file = newFile
callback && callback(file)
}, file.file.type || 'image/png');
}, 50)
}
JS通过canvas进行图片压缩
于 2022-07-04 15:15:40 首次发布