如下所示:
这个需求针对用户上传手机拍摄照片等不便修改图片大小的情况,我们允许上传10M以内的图片由前端对图片进行压缩再传给后台存储,结合elementUI的el-upload组件实现图片上传功能(简单来说就是用户是老大)
1、提取出压缩方法,放在公共方法.js文件里
/** 图片压缩,默认同比例压缩 * @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上传组件
<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="/UploadFiles/2021-04-02/dialogImageUrl">
3、主要在handlePictureCardPreview方法里调用压缩方法
先在当前vue页面import公共js文件
import { compress } from '@/utils'
然后
// 图片预览 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限制上传图片尺寸、大小、比例
我就废话不多说了,大家还是直接看代码吧~
// 上传前判断 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)图片压缩,默认同比例压缩操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。