如下所示:
这个需求针对用户上传手机拍摄照片等不便修改图片大小的情况,我们允许上传10m以内的图片由前端对图片进行压缩再传给后台存储,结合elementui的el-upload组件实现图片上传功能(简单来说就是用户是老大)
1、提取出压缩方法,放在公共方法.js文件里
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
/** 图片压缩,默认同比例压缩
* @param {object} fileobj
* 图片对象
* 回调函数有一个参数,base64的字符串数据
*/
export function compress(fileobj, callback) {
try {
const image = new image()
image.src = url.createobjecturl(fileobj)
image.onload = function () {
const that = this
// 默认按比例压缩
let w = that.width
let h = that.height
const scale = w / h
w = fileobj.width || w
h = fileobj.height || (w / scale)
let quality = 0.7 // 默认图片质量为0.7
// 生成canvas
const canvas = document.createelement( 'canvas' )
const ctx = canvas.getcontext( '2d' )
// 创建属性节点
const anw = document.createattribute( 'width' )
anw.nodevalue = w
const anh = document.createattribute( 'height' )
anh.nodevalue = h
canvas.setattributenode(anw)
canvas.setattributenode(anh)
ctx.drawimage(that, 0, 0, w, h)
// 图像质量
if (fileobj.quality && fileobj.quality <= 1 && fileobj.quality > 0) {
quality = fileobj.quality
}
// quality值越小,所绘制出的图像越模糊
const data = canvas.todataurl( 'image/jpeg' , quality)
// 压缩完成执行回调
const newfile = convertbase64urltoblob(data)
callback(newfile)
}
} catch (e) {
console.log( '压缩失败!' )
}
}
function convertbase64urltoblob(urldata) {
const bytes = window.atob(urldata.split( ',' )[1]) // 去掉url的头,并转换为byte
// 处理异常,将ascii码小于0的转换为大于0
const ab = new arraybuffer(bytes.length)
const ia = new uint8array(ab)
for (let i = 0; i < bytes.length; i++) {
ia[i] = bytes.charcodeat(i)
}
return new blob([ab], { type: 'image/png' })
}
|
2、el-upload上传组件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
<el-form-item ref= "uploadelement" prop= "picurl" class= "upload-img-form" label-width= "0" >
<el-upload
ref= "uploadxls"
class= "avatar-uploader upload-img"
:disabled= "disabled"
:auto-upload= "false"
:style= "{height:'66px', backgroundimage:'url(' + dialogimageurl + ')', backgroundrepeat:'no-repeat', backgroundposition:'center', backgroundsize: '100%,100%'}"
action= "aaa"
::limit= "1"
:show-file-list= "false"
:on-change= "handlepicturecardpreview"
:before-upload= "beforeupload"
accept= "image/png,image/gif,image/jpg,image/jpeg"
>
<!--<img v- if = "dialogimageurl" :src= "dialogimageurl" class= "avatar" >-->
<i v- if = "!dialogimageurl" class= "el-icon-plus avatar-uploader-icon" />
<!--<i v-show= "!dialogimageurl" class= "upload-icon" />
<div v-show= "!dialogimageurl" slot= "tip" class= "el-upload__text upload__tip" >上传实景图</div>-->
<div v- if = "showdelete" class= "remove-img" ><i class= "el-icon-delete" @click.stop= "removeimg" /></div>
<div slot= "tip" class= "el-upload__tip" >
<p><span style= "color:#f5222d;" >*</span>上传楼宇实景图</p>
<p>支持:.jpg .png .gif格式 建议比例:16:9,小于10m</p>
</div>
</el-upload>
</el-form-item>
|
3、主要在handlepicturecardpreview方法里调用压缩方法
先在当前vue页面import公共js文件
import { compress } from '@/utils'
然后
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
// 图片预览
handlepicturecardpreview(file) {
const _that = this
const islt10m = file.size / 1024 / 1024 < 10
if (!islt10m) {
this .$message.error( '上传图片大小不能超过 10m!' )
return false
} else {
this .dialogimageurl = url.createobjecturl(file.raw)
compress(file.raw, function (val) {
_that.theform.picurl = val
_that.imgfile = val
_that.showdelete = true
_that.$refs[ 'addbuildingform' ].validatefield( 'picurl' )
})
}
}
|
compress传入file.raw作为fileobj
这样只要上传图片就进行图片压缩
补充知识:element upload限制上传图片尺寸、大小、比例
我就废话不多说了,大家还是直接看代码吧~
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
// 上传前判断
public async beforeupload(file: any) {
const is1m = file.size / 1024 / 1024 < 3; // 限制小于3m
if (!is1m) {
this .$message.error( '图片尺寸限制最小为270 x 270,大小不可超过3mb,比例为1:1' );
return false ;
} else {
const issize = new promise((resolve, reject) => {
const width = 270;
const height = 270;
const _url = window.url || window.webkiturl;
const img = new image();
img.onload = () => {
const valid = img.width >= width && img.height >= height && img.width === img.height;
valid ? resolve() : reject();
};
img.src = _url.createobjecturl(file);
}).then(
() => {
return file;
},
() => {
this .$message.error( '图片尺寸限制最小为270 x 270,大小不可超过3mb,比例为1:1' );
return promise.reject();
},
);
return issize;
}
}
|
看了很多还不如自己撸一个
以上这篇vue+elementui(el-upload)图片压缩,默认同比例压缩操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/liona_koukou/article/details/84860899