vue + element 上传文件组件压缩图片
export function compressImage ( e) {
return new Promise ( ( resolve, reject) => {
let thumb = ''
let isLt1M = e. size / 1024 / 1024 < 0.5 ;
if ( ! isLt1M) {
reject ( )
}
let img = new Image ( ) ;
let reader = new FileReader ( )
let canvas = document. createElement ( 'canvas' ) ;
let context = canvas. getContext ( '2d' ) ;
reader. readAsDataURL ( e) ;
reader. onload = function ( e) {
img. src = e. target. result;
img. onload = function ( ) {
let originWidth = this . width;
let originHeight = this . height;
let maxWidth = 64 , maxHeight = 64 ;
let targetWidth = originWidth, targetHeight = originHeight;
if ( originWidth > maxWidth || originHeight > maxHeight) {
if ( originWidth / originHeight > maxWidth / maxHeight) {
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) ;
thumb = canvas. toDataURL ( 'image/jpeg' )
if ( img. src. length === 0 ) {
reject ( false )
}
let imgdata = {
content: img. src. slice ( img. src. indexOf ( ',' ) + 1 , img. src. length) ,
thumb: thumb. slice ( thumb. indexOf ( ',' ) + 1 , thumb. length) ,
}
resolve ( imgdata)
}
} ;
} )
}
async materialUpload ( file) {
let isLt1M = file. size / 1024 / 1024 < 0.5 ;
if ( ! isLt1M) {
this . $message. warning ( '上传文件大小不能超过 500kb!' ) ;
}
this . fileimg = await this . $utils. compressImage ( file)
}