let form_data = new FormData();
form_data.append("file", document.getElementById("upfile").files[0]);
let file = document.getElementById("upfile").files[0]
if(file.size > 2097152){
const imged = this.readImg(file)
imged.then((res) => {
const blob = that.compressImg(res, file.type, 300, 300)
blob.then((res) => {
let formData = new FormData()
formData.append('file', res, 'xxx.jpg')
//上传图片到服务器
}).catch(err => {
console.log(err)
})
}).catch((err) => {
})
}else{
//上传图片到服务器
}
readImg(file) {
return new Promise((resolve, reject) => {
const img = new Image()
const reader = new FileReader()
reader.readAsDataURL(file)
reader.onload = function (e) {
img.src = e.target.result
}
reader.onerror = function (e) {
reject(e)
}
img.onload = function () {
resolve(img)
}
img.onerror = function (e) {
reject(e)
}
})
},
compressImg(img, type, mx, mh) {
return new Promise((resolve, reject) => {
const canvas = document.createElement('canvas')
const context = canvas.getContext('2d')
const {width: originWidth, height: originHeight} = img
// 最大尺寸限制
const maxWidth = mx
const maxHeight = mh
// 目标尺寸
let targetWidth = originWidth
let 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))
}
}
canvas.width = targetWidth
canvas.height = targetHeight
context.clearRect(0, 0, targetWidth, targetHeight)
// 图片绘制
context.drawImage(img, 0, 0, targetWidth, targetHeight)
canvas.toBlob(function (blob) {
resolve(blob)
}, type || 'image/png')
})
},
js压缩图片
最新推荐文章于 2024-08-25 09:57:22 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)