vue 图片等比例缩放上传

2023-12-14 12:19:00

需求:上传图片之前按比例缩小图片分辨率,宽高不超过1920不处理图片,宽高超过1920则缩小图片分辨率,如果是一张图片请参考这篇博客:js实现图片压缩、分辨率等比例缩放
我根据这篇博主的分享,写下了我的循环上传的分辨率等比缩小
功能:点击+号,新增一项,点击- 号 删除一项
在这里插入图片描述
:auto-upload="false" 使用elementUI组件不能使他自动上传,主要功能是上传最左边的图片

 <el-form ref="form" :model="form"  label-width="120px">
 	<el-form-item label="资源列表:">
       <div class="ziyuan" flex v-for="(item, indexes) in  addList " :key="item.idxxx">
           <div style="margin-top: 9px;">
           //图片(主要功能在这里)
               <el-upload :action="domins + '/common/upload'"
                   :class="{ disabled: item.uploadDisabled }" list-type="picture-card"
                   
                   :auto-upload="false"
                   :on-remove="handleRemove.bind(null, { 'index': indexes, 'data': item })"
                  
                   :on-change="handleChange.bind(null, { 'index': indexes, 'data': item })"
                   :file-list="item.fileList" accept="image/png, image/jpeg">
                   <i class="el-icon-plus"></i>
               </el-upload>
               <el-dialog :visible.sync="dialogVisible">
                   <img width="100%" :src="item.dialogImageUrl" alt="">
               </el-dialog>

           </div>
           <div class="yasuo" flex="cross:center">
               <div>
                   <div style="height: 68px;">
                   //压缩包
                       <el-upload ref="uploadzip" :action="domins + '/common/upload'"
                           :before-upload="beforeUploadZip" :on-remove="handleRemoveZip"
                           :on-success="handleAvatarSuccessZip.bind(null, { 'index': indexes, 'data': item })"
                           :file-list="item.fileListZip" :auto-upload="true" accept=".zip ,.mp4"
                           :limit="1">
                           <el-button size="small" type="primary">选择资源包</el-button>
                       </el-upload>
                   </div>
               </div>
           </div>
           <div class="airadio">
               <el-radio-group v-model="item.way" >
                   <el-radio :label="0">Android</el-radio>
                   <el-radio :label="1">ios</el-radio>
                   <el-radio :label="2">视频</el-radio>
               </el-radio-group>
           </div>
           <div style="margin-top: 11px;">
           //  '+'
               <i class="el-icon-circle-plus-outline" style="color: #264E71;"
                   @click="plusOne(indexes)"></i>
                     //  '+'
               <i class="el-icon-remove-outline" style="color: #264E71;" v-show="addList.length > 1"
                 @click="removeOne(indexes, item.id, item)"></i>

           </div>
       </div>
   </el-form-item>
 </el-form>

代码:

<script>
// 等比例缩小图片
function imageScale(width, originWidth, originHeight) {
    const scaleRatio = width / originWidth;
    const scaleHeight = scaleRatio * originHeight;
    return [width, scaleHeight];
}

export default {
    components: {  },
    data() {
        return {
       	 	form: {},
       	 	addList: [{
                id: 0,
                uploadDisabled: false,
                album: '',
                zip: '',
                way: 0,
                idxxx: 0
            }],
        }
    },
    methods:{
    	handleRemove(obj, file, fileList) {
            let index = obj.index;

            this.addList[index].uploadDisabled = false
            this.$forceUpdate()
        },
        // 处理图片
        compress(file, scaleWidth, quality = 0.5) {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                console.log(file, 'file----');
                reader.readAsDataURL(file.raw);
                reader.onload = (e) => {
                    let img = new Image();
                    img.src = e.target.result;
                    img.onload = function () {
                        // 等比例缩放图片
                        const [width, height] = imageScale(
                            scaleWidth,
                            img.width,
                            img.height
                        );
                        let canvas = document.createElement("canvas");
                        img.width = canvas.width = width;
                        img.height = canvas.height = height;
                        let ctx = canvas.getContext("2d");
                        ctx.drawImage(img, 0, 0, img.width, img.height);
                        canvas.toBlob(
                            (blob) => {
                                resolve(blob);
                            },
                            "image/jpeg",
                            quality
                        );
                    };

                    img.onerror = function () {
                        reject();
                    };
                };
            });
        },
        handleChange(obj, file, fileList) {
            console.log(file, fileList, 'file, fileList识别图路径');
            if (fileList.length >= 1) {
                let reader = new FileReader()
                reader.readAsDataURL(file.raw) // 必须用file.raw
                reader.onload = () => {
                
                    let img = new Image()
                    img.src = reader.result

                    img.onload = () => {
                        console.log(img.width, 'img.width');
                        console.log(img.height, 'img.height');
                        // 宽高超过1920则缩小图片分辨率
                        if (img.width > 1920 || img.width == 1920 || img.height > 1920 || img.height == 1920) {
                            this.compress(file, 1024).then((blob) => {
                            // 根据后端的要求传数据,如果要求是blob,则不需要处理数据,我这边需求是上传file文件流
                            //处理成file文件流 

                                let f = new File([blob], 'image.jpg', { type: 'image/jpeg' })
                                var form = {};
                                form = new FormData();
                                form.append('file', f);
                                this.$axios.post(this.domins + '/common/upload', form).then((res) => {

                                    let index = obj.index;

                                    this.addList[index].uploadDisabled = true
                                    this.addList[index].album = res.data.data.fullurl
                                    console.log(this.addList, '==addList==');
                                })
                            });
                        } else {
							//宽高不超过1920不处理图片
                            let form = {};
                            form = new FormData();
                            // form 需要的是el-upload 中的file.row
                            form.append('file', file.raw);

                            this.$axios.post(this.domins + '/common/upload', form).then((res) => {
                                let index = obj.index;
                                this.addList[index].uploadDisabled = true
                                this.addList[index].album = res.data.data.fullurl
                                console.log(this.addList, '==addList=3333=');
                            })
                        }
                    }
                }

            }


        },
    }
}
</script>

在这里插入图片描述

文章来源:https://blog.csdn.net/sumimg/article/details/134980094
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。