element-ui 图片压缩上传功能实现
更新时间:2023年10月24日 11:40:17 作者:黑白两客
这篇文章主要介绍了element-ui 图片压缩上传功能实现,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧
element-ui 图片压缩上传
export const compressImgNew = (file) => { 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') // 画布为2d // const width = image.width / 1.05 // 图片宽度 / 压缩比例 // const height = image.height / 1.05 // 图片高度 / 压缩比例 const width = image.width / 3 // 图片宽度 / 压缩比例 const height = image.height / 3 // 图片高度 / 压缩比例 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 = dataURLtoBlob(dataUrl, file.type) //图片转二进制 resolve(blobData) } reader.onload = e => { image.src = e.target.result } reader.readAsDataURL(file) }) }; //图片转二进制 function dataURLtoBlob(dataURL, type) { var binary = atob(dataURL.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 }) }
使用
import { compressImgNew } from “@/assets/js/picture.js”;
beforeAvatarUpload(file) { let types = [ "image/jpeg", "image/jpg", "image/png" ]; const isImage = types.includes(file.type); const isLtSize = file.size / 1024 / 1024 < 5; if (!isImage) { this.$message.warning("上传图片只能是 JPG、JPEG、PNG 格式!"); return false; } if (!isLtSize) { this.$message.warning("上传图片大小不能超过 5MB!"); return false; } return compressImgNew(file); },
到此这篇关于element-ui 图片压缩上传的文章就介绍到这了,更多相关element-ui 图片上传内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
javascript getElementsByTagName
DC大神为早期不支持getElementsByTagName的浏览器写的hack,当然与原生的不能同日而言,原生的用到缓存机制呢。2011-01-01解决Babylon.js中AudioContext was not allowed&nbs
这篇文章主要介绍了解决Babylon.js中AudioContext was not allowed to start异常问题方法详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2023-04-04JavaScript性能优化 创建文档碎片(document.createDocumentFragment)
讲这个方法之前,我们应该先了解下插入节点时浏览器会做什么。2010-07-07拖动Html元素集合 Drag and Drop any item
拖动Html元素集合 Drag and Drop any item...2006-12-12
最新评论