function compressImage(path) {
//压缩图片
let ImageWidth = 750
return new Promise((resolve, reject) => {
let maxSize = 2 * 1024 * 1024
if (path.file.size < maxSize) {
resolve(path.file)
} else {
var canvas = document.createElement('canvas')
var ctx = canvas.getContext('2d')
var img = new Image()
img.src = path.url
var file
img.onload = function () {
var width = img.width > ImageWidth ? ImageWidth : img.width
var height =
img.width > ImageWidth ? width * (img.height / img.width) : img.height
canvas.width = width
canvas.height = height
ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
/**
* 0 ~ 1
*/
var base64 = canvas.toDataURL('image/jpeg', 0.7)
//base64转file
var arr = base64.split(','),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
}
file = new File([u8arr], new Date().getTime() + '.jpg', {
type: mime,
})
resolve(file)
}
}
})
}
前端实现图片压缩,传给后端
最新推荐文章于 2024-01-15 17:30:46 发布