1. 程式人生 > >VUE彈框上傳圖片+預覽+壓縮圖片

VUE彈框上傳圖片+預覽+壓縮圖片

先看一下實現效果


 

 

這裡彈出框我使用了一個外掛---------YDUI,一隻注重審美,且效能高效的移動端&微信UI。

安裝:

$ npm install vue-ydui --save

 

在入口檔案中配置:

import YDUI from 'vue-ydui'; /* 相當於import YDUI from 'vue-ydui/ydui.rem.js' */
import 'vue-ydui/dist/ydui.rem.css';
/* 使用px:import 'vue-ydui/dist/ydui.px.css'; */
Vue.use(YDUI);

 

 HTML程式碼

<template>
  <div id="hallsettings">
    <div class="user-list">
      <ul>
        <li class="picture" >
          <span>我的相簿</span>
          <div class="picture-list">
            <div v-for="item in myGalleryList
" class="picture-item" @click="openCustomConfrim(item.fullUrl)"> <img :src="item.fullUrl" width="60px" height="60px"/> </div> <div @click="openCustomConfrim(null)" class="addPicture"> + </div> </div> </li> </ul> </div> <!-- 上傳圖片 --> <input @change="
fileChange($event)" type="file" id="upload_file" multiple style="display: none"/> </div> </template>

 

 JS程式碼

 

export default {
  data() {
    return {
      size:0,//圖片大小

    };
  },
  methods: {
    openCustomConfrim(fullUrl) {
      this.$dialog.confirm({
        title: "上傳圖片",
        mes:
          '<div style="width:277px;height:170px;"><img id="uploadImg" src="'+(fullUrl==null?'':fullUrl)+'" alt="" width="100%" height="100%"/></div>',
        opts: [
          {
            txt: "上傳",
            color: true,
            stay: true,
            callback: () => {
              document.getElementById('upload_file').click();
            }
          },
          {
            txt: "儲存",
            color: true,
            callback: () => {
              var uploadImg = document.getElementById("uploadImg").src;
              if(uploadImg == ""){//未選擇圖片
                this.$dialog.toast({
                    mes: '請選擇要上傳的圖片',
                    timeout: 1500
                });
                return;
              }
              //在這裡進行圖片上傳操作

              document.getElementById("uploadImg").src = '';//儲存成功後清除src屬性的值
            }
          },
          {
            txt: "取消",
            color: false,
            callback: () => {
              document.getElementById("uploadImg").src = '';
            }
          }
        ]
      });
    },
    fileChange(el) {
      if (!el.target.files[0].size) return;
      this.fileList(el.target);
      el.target.value = "";
    },
    fileList(fileList) {
      let files = fileList.files;
      for (let i = 0; i < files.length; i++) {
        //判斷是否為資料夾
        if (files[i].type != "") {
          this.fileAdd(files[i]);
        } else {
          //資料夾處理
          this.folders(fileList.items[i]);
        }
      }
    },
    //資料夾處理
    folders(files) {
      let _this = this;
      //判斷是否為原生file
      if (files.kind) {
        files = files.webkitGetAsEntry();
      }
      files.createReader().readEntries(function(file) {
        for (let i = 0; i < file.length; i++) {
          if (file[i].isFile) {
            _this.foldersAdd(file[i]);
          } else {
            _this.folders(file[i]);
          }
        }
      });
    },
    foldersAdd(entry) {
      let _this = this;
      entry.file(function(file) {
        _this.fileAdd(file);
      });
    },
    fileAdd(file) {
      //總大小
      this.size = this.size + file.size;
      //判斷是否為圖片檔案
      if (file.type.indexOf("image") == -1) {
        this.$dialog.toast({
          mes: '請選擇圖片檔案',
          timeout: 1500
        });
        return;
      } else {
        let reader = new FileReader();
        let _this = this;
        reader.readAsDataURL(file);
        reader.onloadend = function() {
          let result = this.result;
          let image = new Image();
          image.src = result;
          if(this.result.length <= 100 * 1024){
            image.onload = function() {
              image.src = file.src;
            };
          }else{//圖片壓縮
            image.onload = function() {
              let data = _this.compress(image);
              this.result = data;
            };
            image.src = this.result;
          }
          document.getElementById("uploadImg").src = image.src;
        };
      }
    },
    compress(img){
      let canvas = document.createElement("canvas");
      let ctx = canvas.getContext("2d");
      //瓦片canvas
      let tCanvas = document.createElement("canvas");
      let tctx = tCanvas.getContext("2d");
      let initSize = img.src.length;
      let width = img.width;
      let height = img.height;
      //如果圖片大於四百萬畫素,計算壓縮比並將大小壓至400萬以下
      let ratio;
      if ((ratio = width * height / 4000000) > 1) {
        console.log("大於400萬畫素");
        ratio = Math.sqrt(ratio);
        width /= ratio;
        height /= ratio;
      } else {
        ratio = 1;
      }
      canvas.width = width;
      canvas.height = height;
      //鋪底色
      ctx.fillStyle = "#fff";
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      //如果圖片畫素大於100萬則使用瓦片繪製
      let count;
      if ((count = width * height / 1000000) > 1) {
        console.log("超過100W畫素");
        count = ~~(Math.sqrt(count) + 1); //計算要分成多少塊瓦片
        //            計算每塊瓦片的寬和高
        let nw = ~~(width / count);
        let nh = ~~(height / count);
        tCanvas.width = nw;
        tCanvas.height = nh;
        for (let i = 0; i < count; i++) {
          for (let j = 0; j < count; j++) {
            tctx.drawImage(
              img,
              i * nw * ratio,
              j * nh * ratio,
              nw * ratio,
              nh * ratio,
              0,
              0,
              nw,
              nh
            );
            ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
          }
        }
      } else {
        ctx.drawImage(img, 0, 0, width, height);
      }
      
      //進行最小壓縮
      let ndata = canvas.toDataURL("image/jpeg", 0.1);
      console.log("壓縮前:" + initSize);
      console.log("壓縮後:" + ndata.length);
      console.log(
        "壓縮率:" + ~~(100 * (initSize - ndata.length) / initSize) + "%"
      );
      tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
      return ndata;
    }
  },
  mounted() {
  }
};                        

 

 

 

 

 

 如果有什麼不對的地方,請指出!感激不盡!(創作不易!轉載請註明出處!)