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-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>
// 引入image-conversion
import * as imageConversion from 'image-conversion'
//图片超过500k压缩  宽度超过1080等比缩放
		beforeAvatarUpload(file) {
			console.log(this.data);
			let otherData = this.data
			const check = this.uploadList.length < this.num;
			if (!check) {
				this.$Message.warning(`上传图片不超过${this.num}张。`);
			} else {
				const image = new Image();
				const size = file.size / 1024
				console.log(`压缩前${size}k`)
				let name = this.getDiffName(file.name)
				if (name == '图片') {
					return new Promise((resolve) => {
						if (size >= 500) {
							let imgWidth = 0
							let imgHeigth = 0
							image.onload = function () {
								imgWidth = this.width
								imgHeigth = this.height
								console.log("图片宽度:", this.width);
								console.log("图片高度:", this.height);
								let scaleNum = imgWidth > 1080 ? (imgWidth / 1080).toFixed(2) : 1
								imgHeigth = (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 = otherData
									console.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.data
            const check = this.uploadList.length < this.num;
            if (!check) {
                this.$Message.warning(`上传图片不超过${this.num}张。`);
            } else {
                const image = new Image();
                const size = file.size / 1024
                console.log(`压缩前${size}k`)
                let name = this.getDiffName(file.name)
                if (name == '图片') {
                    return new Promise((resolve) => {
                        if (size >= 500) {
                            let imgWidth = 0
                            let imgHeigth = 0
                            image.onload = function () {
                                imgWidth = this.width
                                imgHeigth = this.height
                                console.log("图片宽度:", this.width);
                                console.log("图片高度:", this.height);
                                let scaleNum = imgWidth > 1080 ? (imgWidth / 1080).toFixed(2) : 1
                                imgHeigth = (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 = otherData
                                    console.log(`压缩后${res.size / 1024}k`)
                                    resolve(res)
                                })
                                // 这里可以根据需要进行其他操作或处理
                            };
                            image.src = URL.createObjectURL(file); // 将文件转换为URL地址并加载到image对象中

                        } else {
                            resolve(file)
                        }
                    })
                }
            }
        },
    },
    mounted() { },
};
</script>
<style lang="less" scoped></style>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值