第一种方法:需要安装一个模块
yarn add image-conversion --save
<el-upload
ref="upload"
:data="date"
:action="URL+'/api/post/file'"
:before-upload="beforeAvatarAUDIO3" //将用到此方法
:on-success="handleAvatarAUDIO3"
:on-error="error3"
:file-list="fileList"
>
第一种方法,需要引入imageConversion
import imageConversion from 'image-conversion'
beforeAvatarAUDIO3(file) { //第一种方法开始------------------------------------------------------------------------- return new Promise((resolve, reject) => { let _URL = window.URL || window.webkitURL // let isLt2M = file.size / 1024 / 1024 > 2 // 判定图片大小是否小于4MB // 这里需要计算出图片的长宽 let img = new Image() img.onload = function () { file.width = img.width // 获取到width放在了file属性上 file.height = img.height // 获取到height放在了file属性上 let valid = img.width > 1280 // 图片宽度大于1280 // compressAccurately有多个参数时传入对象 if (valid) { imageConversion.compressAccurately(file, { size: 1024, //图片大小压缩到1024kb 1280 //宽度压缩到1280 }).then(res => { resolve(res) }) } else resolve(file) } // 需要把图片赋值 img.src = _URL.createObjectURL(file) }) //第一种方法结束---------------------------------------------------------------------------------
//第二种方法(改变图片分辨率大小实现压缩)----------------------------------------------------------------- const _this = this return new Promise(resolve => { const reader = new FileReader() const image = new Image() image.onload = (imageEvent) => { const canvas = document.createElement('canvas'); const context = canvas.getContext('2d'); let width = image.width; let height = image.height;
//等比缩放第一种 宽或高超过1280,进行等比例缩放
let rate = image.width / image.height if (width > 1280 || height > 1280) { width = rate > 1 ? 1280 : 1280 * rate; height = rate < 1 ? 1280 : 1280 / rate; }
//等比缩放第二种 宽或高超过1280,等比缩放
let rate = 1280 / width > 1;
let tate = 1280 / height > 1;
if(!rate){
let product = 1280 / width
width = Math.floor((width * product)*100)/100
height = Math.floor((height * product)*100)/100
}else if(!tate){
let product = 1280 / height
width = Math.floor((width * product)*100)/100
height = Math.floor((height * product)*100)/100
}
canvas.width = width; canvas.height = height; context.clearRect(0, 0, width, height); context.drawImage(image, 0, 0, width, height); const dataUrl = canvas.toDataURL(file.type); const blobData = _this.dataURItoBlob(dataUrl, file.type); resolve(blobData) } reader.onload = (e => { image.src = e.target.result; }); reader.readAsDataURL(file); })
//第二种方法结束-----------------------------------------------------------------------------------
},
dataURItoBlob(dataURI, type) { var binary = atob(dataURI.split(',')[1]); var array = []; for(var i = 0; i < binary.length; i++) { array.push(binary.charCodeAt(i)); } return new Blob([new Uint8Array(array)], {type: type}); },