当前位置: 首页 > news >正文

js+views 压缩上传的图片

安装image-conversion插件,在before-upload方法中对上传的图片文件进行处理

遇到的问题:
1、因为在上传文件之前的钩子中对图片进行了压缩处理,所以组件中上传的data会丢失,需要重新赋值
2、imageConversion 的引入需要使用import * as imageConversion from 'image-conversion,否则无法生效

线上图片压缩工具https://tinypng.com/

1、安装

npm install image-conversion --save

2、代码中使用

<el-uploadclass="avatar-uploader"action="":data="data" :on-success="handleAvatarSuccess":before-upload="beforeAvatarUpload"><img v-if="imageUrl" :src="imageUrl" class="avatar"><i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
// 引入image-conversion
import * as imageConversion from 'image-conversion'
//图片超过500k压缩  宽度超过1080等比缩放beforeAvatarUpload(file) {console.log(this.data);let otherData = this.dataconst check = this.uploadList.length < this.num;if (!check) {this.$Message.warning(`上传图片不超过${this.num}张。`);} else {const image = new Image();const size = file.size / 1024console.log(`压缩前${size}k`)let name = this.getDiffName(file.name)if (name == '图片') {return new Promise((resolve) => {if (size >= 500) {let imgWidth = 0let imgHeigth = 0image.onload = function () {imgWidth = this.widthimgHeigth = this.heightconsole.log("图片宽度:", this.width);console.log("图片高度:", this.height);let scaleNum = imgWidth > 1080 ? (imgWidth / 1080).toFixed(2) : 1imgHeigth = (imgHeigth / scaleNum).toFixed(2)console.log("图片宽度`:", scaleNum);console.log("图片高度`:", imgHeigth);let resizeSize = (size / 5) >= 500 ? size / 5 : 500// imageConversion.compressAccurately(file, { width: 1080, height: imgHeigth, size: 600 }).then(res => {imageConversion.compressAccurately(file, resizeSize).then(res => {res = new File([res], file.name, { type: res.type, lastModified: Date.now() })this.data = otherDataconsole.log(`压缩后${res.size / 1024}k`)resolve(res)})// 这里可以根据需要进行其他操作或处理};image.src = URL.createObjectURL(file); // 将文件转换为URL地址并加载到image对象中} else {resolve(file)}})}}},getDiffName(fileName) {let name = "";let type = fileName.substring(fileName.lastIndexOf(".") + 1);if (["wav", "aac", "mp3"].indexOf(type) >= 0) name = "音频";else if (["mp4", "avi", "mov", "rmvb"].indexOf(type) >= 0) name = "视频";else if (["txt", "doc", "xls", "xlsx", "ppt", "pdf", "docx", "pptx"].indexOf(type) >= 0)name = "文件";else name = "图片";return name;},

完整代码

<template><div><el-upload class="avatar-uploader" action="" :data="data" :on-success="handleAvatarSuccess":before-upload="beforeAvatarUpload"><img v-if="imageUrl" :src="imageUrl" class="avatar"><i v-else class="el-icon-plus avatar-uploader-icon"></i></el-upload></div>
</template>
<script>
// 引入image-conversion
import * as imageConversion from 'image-conversion'
export default {data() {return {};},computed: {},methods: {getDiffName(fileName) {let name = "";let type = fileName.substring(fileName.lastIndexOf(".") + 1);if (["wav", "aac", "mp3"].indexOf(type) >= 0) name = "音频";else if (["mp4", "avi", "mov", "rmvb"].indexOf(type) >= 0) name = "视频";else if (["txt", "doc", "xls", "xlsx", "ppt", "pdf", "docx", "pptx"].indexOf(type) >= 0)name = "文件";else name = "图片";return name;},//图片超过1M压缩  宽度超过800等比缩放handleBeforeUpload(file) {console.log(this.data);let otherData = this.dataconst check = this.uploadList.length < this.num;if (!check) {this.$Message.warning(`上传图片不超过${this.num}张。`);} else {const image = new Image();const size = file.size / 1024console.log(`压缩前${size}k`)let name = this.getDiffName(file.name)if (name == '图片') {return new Promise((resolve) => {if (size >= 500) {let imgWidth = 0let imgHeigth = 0image.onload = function () {imgWidth = this.widthimgHeigth = this.heightconsole.log("图片宽度:", this.width);console.log("图片高度:", this.height);let scaleNum = imgWidth > 1080 ? (imgWidth / 1080).toFixed(2) : 1imgHeigth = (imgHeigth / scaleNum).toFixed(2)console.log("图片宽度`:", scaleNum);console.log("图片高度`:", imgHeigth);let resizeSize = (size / 5) >= 500 ? size / 5 : 500// imageConversion.compressAccurately(file, { width: 1080, height: imgHeigth, size: 600 }).then(res => {imageConversion.compressAccurately(file, resizeSize).then(res => {res = new File([res], file.name, { type: res.type, lastModified: Date.now() })this.data = otherDataconsole.log(`压缩后${res.size / 1024}k`)resolve(res)})// 这里可以根据需要进行其他操作或处理};image.src = URL.createObjectURL(file); // 将文件转换为URL地址并加载到image对象中} else {resolve(file)}})}}},},mounted() { },
};
</script>
<style lang="less" scoped></style>
http://www.lryc.cn/news/304783.html

相关文章:

  • 【安卓基础5】中级控件
  • Arthas—【学习篇】
  • css pointer-events 多层鼠标点击事件
  • k8s中基于alpine的pod无法解析域名问题
  • 缩小ppt文件大小的办法
  • vue3中使用 tui-image-editor进行图片处理,并上传
  • 18.贪心算法
  • [AI]部署安装有道QanyThing
  • NLP_BERT与GPT争锋
  • 放一个还看得过去的后台模板设置模块css样式框架
  • 关于信号强度单位dB和dBm区别
  • 华清远见作业第四十二天——Qt(第四天)
  • vue2和vue3区别 浅析
  • GIT使用和简介
  • HTTPS(超文本传输安全协议)被恶意请求该如何处理。
  • QT-模拟电梯上下楼
  • 基于springboot+vue的桂林旅游景点导游平台(前后端分离)
  • 设计模式四:适配器模式
  • 【AI应用】SoraWebui——在线文生视频工具
  • 电路设计(27)——交通信号灯的multisim仿真
  • Python Sanic 异步 Web 框架
  • 滚雪球学Java(70):深入理解Java中的PriorityQueue底层实现与源码分析
  • 李宏毅2023机器学习作业1--homework1
  • Mysql的SQL调优-面试
  • Unity 2021.3发布WebGL设置以及nginx的配置
  • 【鸿蒙 HarmonyOS 4.0】数据持久化
  • mysql mgr集群多主部署
  • 【开源】JAVA+Vue.js实现医院门诊预约挂号系统
  • 《图解设计模式》笔记(一)适应设计模式
  • 图文说明Linux云服务器如何更改实例镜像