天天看點

vue實作圖檔裁剪後上傳

一、背景

目前負責的系統(商城背景管理系統)裡面有這麼一個需求,為了配合前台的展示,上傳的商品圖檔比較必須是1:1的正方形。(其它地方有時會有5:4或者16:9的需求,但較少)。是以需要對上傳的圖檔先進行裁剪,并且按要求隻能裁剪為1:1,然後在進行上傳。

當然,為了相容系統其它地方有5:4或者16:9的圖檔比例需求,需要給出一個參數,可以随時控制圖檔裁剪的比例。

二、使用什麼插件實作

使用 vue-cropper 顯示,該插件是基于 cropper 的二次封裝,簡單小巧,更合适vue項目。注意:功能沒有 cropper 強大。

三、使用 cropper

3.1 封裝一下cropper, 配置自己想要的參數

<template>
  <div class="Cropper">
    <el-dialog
      :visible.sync="dialogVisible"
      width="740px"
      title="圖檔裁剪"
      :before-close="handleClose"
      :close-on-click-modal="false">
      <div
        class="cropper-container">
        <div class="cropper-el">
          <vue-cropper
            ref="cropper"
            :img="cropperImg"
            :output-size="option.size"
            :output-type="option.outputType"
            :info="true"
            :can-move="option.canMove"
            :can-move-box="option.canMoveBox"
            :fixed-box="option.fixedBox"
            :auto-crop="option.autoCrop"
            :auto-crop-width="option.autoCropWidth"
            :auto-crop-height="option.autoCropHeight"
            :center-box="option.centerBox"
            :high="option.high"
            :info-true="option.infoTrue"
            @realTime="realTime"
            :enlarge="option.enlarge"
            :fixed="option.fixed"
            :fixed-number="option.fixedNumber"
            :limitMinSize="option.limitMinSize"
          />
        </div>
        <!-- 預覽  ==>> 我不需要預覽 -->
        <!-- <div class="prive-el">
          <strong>預覽:</strong>
          <div class="prive-style" :style="{'width': '200px', 'height': '200px', 'overflow': 'hidden', 'margin': '10px 25px', 'display':'flex', 'align-items' : 'center'}">
          <div class="prive-style" :style="{'width': previews.w + 'px', 'height': previews.h + 'px',  'overflow': 'hidden', 'margin': '10px 25px', 'display':'flex', 'align-items' : 'center'}">
            <div class="preview" :style="previews.div">
              <img :src="previews.url" :style="previews.img">
            </div>
          </div>
          <el-button @click="uploadBth">重新上傳</el-button>
        </div> -->
      </div>
      <span
        slot="footer"
        class="dialog-footer">
        <el-button @click="uploadBth">重新上傳</el-button>
        <el-button
          @click="handleClose">取 消</el-button>
        <el-button
          type="primary"
          @click="saveImg">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { VueCropper } from 'vue-cropper';
export default {
  name: 'Cropper',
  components: {
    VueCropper
  },
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    imgType: {
      type: String,
      default: 'blob'
    },
    cropperImg: {
      type: String,
      default: ''
    },
    zoomScale: {      // 裁剪比例,預設1:1
      type: Array,
      default: [1, 1]
    }
  },
  data () {
    return {
      previews: {},
      option: {
        img: '', // 裁剪圖檔的位址
        size: 1, // 裁剪生成圖檔的品質
        outputType: 'png', // 裁剪生成圖檔的格式 預設jpg
        canMove: false, // 上傳圖檔是否可以移動
        fixedBox: false, // 固定截圖框大小 不允許改變
        canMoveBox: true, // 截圖框能否拖動
        autoCrop: true, // 是否預設生成截圖框
        // 隻有自動截圖開啟 寬度高度才生效
        autoCropWidth: 500, // 預設生成截圖框寬度
        autoCropHeight: 500, // 預設生成截圖框高度
        centerBox: true, // 截圖框是否被限制在圖檔裡面
        high: false, // 是否按照裝置的dpr 輸出等比例圖檔
        enlarge: 1, // 圖檔根據截圖框輸出比例倍數
        mode: 'contain', // 圖檔預設渲染方式
        maxImgSize: 2000, // 限制圖檔最大寬度和高度
        // limitMinSize: [500,500], // 更新裁剪框最小屬性
        limitMinSize: 500, // 更新裁剪框最小屬性
        infoTrue: true, // true 為展示真實輸出圖檔寬高 false 展示看到的截圖框寬高
        fixed: true, // 是否開啟截圖框寬高固定比例  (預設:true)
        // fixedNumber: [1, 1] // 截圖框的寬高比例 ==>> 這個參數目前沒有作用(作者解釋的)
        fixedNumber: this.zoomScale // 截圖框的寬高比例
      },
    };
  },
  methods: {
    // 裁剪時觸發的方法,用于實時預覽
    realTime (data) {
      this.previews = data;
    },
    // 重新上傳
    uploadBth () {
      this.$emit('update-cropper');
    },
    // 取消關閉彈框
    handleClose () {
      this.$emit('colse-dialog', false);
    },
    // 擷取裁剪之後的圖檔,預設blob,也可以擷取base64的圖檔
    saveImg () {
      if (this.imgType === 'blob') {
        this.$refs.cropper.getCropBlob(data => {
          this.$emit('upload-img', data);
        });
      } else {
        this.$refs.cropper.getCropData(data => {
          this.uploadFile = data;
          this.$emit('upload-img', data);
        });
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.Cropper {
  .cropper-el {
    height: 700px;
    width: 700px;
    flex-shrink: 0;
  }
  .cropper-container {
    display: flex;
    justify-content: space-between;
    .prive-el {
      flex: 1;
      align-self: center;
      text-align: center;
      .prive-style {
        margin: 0 auto;
        flex: 1;
        -webkit-flex: 1;
        display: flex;
        display: -webkit-flex;
        justify-content: center;
        -webkit-justify-content: center;
        overflow: hidden;
        background: #ededed;
        margin-left: 40px;
      }
      .preview {
        overflow: hidden;
      }
      .el-button {
        margin-top: 20px;
      }
    }
  }
}
</style>
<style lang="scss">
.cropper-box-canvas img{
  width: 100% !important;
  height: 100% !important;
}
</style>           

3.2 将 el-upload 和 cropper 組合,封裝,其他地方可以直接調用

<template>
  <div>
    <!-- 注意:必須關閉自動上傳屬性 auto-upload -->
    <el-upload
      :http-request="Upload"
      :multiple="true"
      list-type="picture-card"
      :file-list="productImageList"
      :on-remove="removeImage"
      :limit="12"
      :before-upload="beforeAvatarUpload"
      ref="fileUpload"
      :auto-upload="false"
      :on-change="selectChange"
      action=""
      class="cropper-upload-box"
    >
      <i slot="default" class="el-icon-plus"></i>
    </el-upload>

    <cropper
      v-if="showCropper"
      :dialog-visible="showCropper"
      :cropper-img="cropperImg"
      :zoomScale="zoomScale"
      @update-cropper="updateCropper"
      @colse-dialog="closeDialog"
      @upload-img="uploadImg"
    />
  </div>
</template>

<script>
import Cropper from "@/components/cropper";
import { client, randomWord } from '@/utils/alioss'
export default {
  name: "CropperUpload",
  data() {
    return {
      productImageList: [],

      showCropper: false, // 是否顯示裁剪框
      cropperImg: "" // 需要裁剪的圖檔
    };
  },
  props: {
    defaultImgList: {     // 預設顯示的圖檔清單
      type: Array,
      default: () => []
    },
    zoomScale: {         // 裁剪比例,預設1:1
      type: Array,
      default: [1, 1]
    }
  },
  components: {
    Cropper
  },
  watch: {
    defaultImgList: {
      handler: function(newVal, oldVal){
        this.productImageList = newVal   // 指派
      },
      deep: true
    }
  },
  methods: {
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;     // 原圖檔
      // const isLt2M = this.uploadFile.size / 1024 / 1024 < 1;     //裁剪後的圖檔(會比原圖檔大很多,應該是轉成Blob的原因導緻)
      if (!isLt2M) {
        this.$message.error("上傳圖檔大小不能超過 2MB!");
        this.noCanUpload = true     // 如果這裡被攔截,将自動删除不能上傳的圖檔
        return false
      }
      // return isLt2M
    },
    removeImage(file, fileList) {
      const index = this.productImageList.findIndex(item => {
        return item.uid == file.uid;
      });
      if (index > -1) {
        this.productImageList.splice(index, 1);
      }
      this.$emit('getUploadImg', this.productImageList)   // 把最新上傳的圖檔清單傳回
    },
    Upload(file) {
      var fileName = `img/${randomWord(
        true,
        20
      )}${+new Date()}${file.file.name.substr(file.file.name.indexOf("."))}`;
      // client().put(fileName, file.file).then(result => {
      client()
        .put(fileName, this.uploadFile)
        .then(result => {
          // 上傳裁剪後的圖檔
          console.log(result);
          this.productImageList.push({
            url: result.url,
            uid: file.file.uid,
            saveUrl: "/" + result.name
          });
          this.showCropper = false;
          this.$emit('getUploadImg', this.productImageList)    // 把最新上傳的圖檔清單傳回
        })
        .catch(err => {
          this.showCropper = false;
          console.log(err);
        });
    },

    // 更新圖檔
    updateCropper() {
      if(!this.noCanUpload){
        let fileList = this.$refs.fileUpload.uploadFiles        // 擷取檔案清單
        let index02 = fileList.findIndex(item => {        // 把取消裁剪的圖檔删除
          return item.uid == this.currentFile.uid;
        });
        fileList.splice(index02, 1)
      }

      let index = this.$refs.fileUpload.$children.length - 1;
      this.$refs.fileUpload.$children[index].$el.click();
    },
    // 關閉視窗
    closeDialog() {
      this.showCropper = false;
      
      if(!this.noCanUpload){
        let fileList = this.$refs.fileUpload.uploadFiles        // 擷取檔案清單
        let index = fileList.findIndex(item => {        // 把取消裁剪的圖檔删除
          return item.uid == this.currentFile.uid;
        });
        fileList.splice(index, 1)
      }
    },
    // 上傳圖檔
    uploadImg(file) {
      this.uploadFile = file;
      // this.$refs.fileUpload.submit();

      // 判斷裁剪後圖檔的寬高
      let img =  new Image()
      img.src = window.URL.createObjectURL(file);     // Blob轉成url 才能給img顯示
      img.onload = () => {
        let minProp = Math.min(img.width, img.height)  //裁剪後的圖檔寬,高  ==> 取最小值
        if( minProp < 500){     // 如果最小值比設定的最小值(預設為500)小
          this.$message.error(`請保證圖檔短邊最小為500`);
          return false
        }
        this.$refs.fileUpload.submit();
      }
    },
    selectChange(file) {
      this.noCanUpload = false
      let files = file.raw;
      var reader = new FileReader();
      reader.onload = e => {
        let data;
        if (typeof e.target.result === "object") {
          // 把Array Buffer轉化為blob 如果是base64不需要
          data = window.URL.createObjectURL(new Blob([e.target.result]));
        } else {
          data = e.target.result;
        }
        this.cropperImg = data;

        // 圖檔圖檔尺寸,如果是正方形,則直接上傳;否則調用裁剪
        let img =  new Image()
        img.src = this.cropperImg;
        img.onload = () => {
          if(img.width == img.height){    // 本來就是正方形 => 直接上傳
            this.uploadFile = files;
            this.$refs.fileUpload.submit();   // 調用上傳方法
          }else{
            this.showCropper = true;      // 不是正方形的圖檔才開啟裁剪
            this.currentFile = file       // 儲存目前操作裁剪的圖檔
          }
        }
      };
      // 轉化為base64
      // reader.readAsDataURL(file)
      // 轉化為blob
      reader.readAsArrayBuffer(files);
      
      // this.showCropper = true;     // 預設開啟裁剪
    }
  }
};
</script>

<style lang="scss">
.cropper-upload-box{
  display: flex;
  .el-upload{
    width: 148px;
    height: 148px;
  }
}
</style>
           

3.3 其他頁面中調用裁剪元件

<!-- 
    zoomScale:定義的裁剪比例;
    defaultImgList: 預設顯示的圖檔清單
    @getUploadImg:這個事件将得到更新後(上傳、删除)的圖檔清單,在頁面中重新指派給預設的清單變量後就可以做頁面中的邏輯處理了
 -->
<cropper-upload :zoomScale='[1,1]' :defaultImgList="productImageList" @getUploadImg="getUploadImg"></cropper-upload>

           

自此,圖檔裁剪功能實作!!!

3.4 看一下頁面中的效果

vue實作圖檔裁剪後上傳

​​​​​​​

文章僅為本人學習過程的一個記錄,僅供參考,如有問題,歡迎指出!