vue + elementUI使用compressorjs上传前压缩图片
Sonder
2020-12-25
3160字
8分钟
浏览 (5.9k)
下载地址
npm install compressorjs
npm install qiniu-js
前提条件
1.我们要求图片的宽度超过600像素,压缩到600像素的宽度,比未经处理的图片低600像素,必须在上传之前计算图像的宽度。
2.具体的压缩参数,请去github的观点,有没有什么帮助的也可以看一下它
代码片段
import Compressor from 'compressorjs'
import * as qiniu from 'qiniu-js'
<el-upload
action="http://upload-z2.qiniup.com"
:data="{token:qiniuToken}"
:http-request="customUpload"
list-type="picture-card"
:disabled="false"
:before-upload="beforeUpload"
:show-file-list="false"
>
beforeUpload method
beforeUpload(file) {
const isJPG = (file.type === 'image/jpeg') || (file.type === 'image/png')
const isLt5M = file.size / 1024 / 1024 < 5
if (!isJPG) {
this. $ message.error ( 'upload pictures only JPG / PNG format!')
}
if (!isLt5M) {
this. $ message.error ( 'upload image size should not exceed 5MB!')
}
// Get image width
const _URL = window.URL || window.webkitURL
const img = new Image()
img.onload = function() {
this.imgWidth = img.width
}
img.src = _URL.createObjectURL(file)
return isJPG && isLt5M
},
customUpload method
customUpload(file) {
const _this = this
// metric is greater than 600 pixels, compression
new Compressor(file.file, {
quality: this.imgWidth > 600 ? 0.8 : 1,
maxWidth: 500,
convertSize: 1000000, // 解决有些图片在1.3M的时候不能压缩的问题
success(compressFile) {
// seven cattle upload
const config = {
useCdnDomain: true, // cdn acceleration indicates whether the domain name, is a Boolean value, true indication, the default is false.
region: null // depending on prompted to modify the upload area, when is null or undefined, automatically upload domain analysis area
}
const putExtra = {
fname: '', // file the original file name
params: {}, // used to place a custom variable
mimeType: null // used to limit upload file type, file type restrictions do not represent is null; limit type in an array: [ "image / png", "image / jpeg", "image / gif"]
}
const observable = qiniu.upload(compressFile, null, file.data.token, putExtra, config)
observable.subscribe({
error: (err) => {
// failure error message
console.log(err)
},
complete: (res) => {
// will return here after the success key, need to deal with their own logic
_this.temp.listPic = _this.qiniuPre + res.key
}
})
},
error(err) {
console.log(err.message)
}
})
},
参数说明
- strict: true, 严格的语法模式
- checkOrientation: true, 检查图片的方向
- quality: 0.8, 默认压缩质量
- maxWidth:300, maxHeight:300, 我觉得头像没必要超过300px
- convertSize: 5000000, png图片如果超过了这个数值,被转换成JPEGs。