史上最全基于vue的圖片裁剪vue-cropper使用

原文地址:https://blog.csdn.net/qq_41107231/article/details/109725839

基于vue的圖片裁剪vue-cropper
最近小編好久沒有寫博客了,今天發(fā)現(xiàn)突然漲了好幾個(gè)粉,特別的開心,為了回饋大家,我今天準(zhǔn)備了一點(diǎn)點(diǎn)小小的心意,最近工作實(shí)在太忙,難得抽空更博了,不過最近小編會(huì)快馬加鞭努力更博的。

新的需求
最近小編遇到一個(gè)圖片裁剪的需求,對(duì)于一個(gè)前端小白的我來說,搞這些花里胡哨的東西,走了很多彎路,各種百度,改了又改,實(shí)則不易啊。廢話不多說上大圖:

vue-cropper官網(wǎng)
鏈接:https://github.com/xyxiao001/vue-cropper

安裝:npm install vue-cropper 或者 yarn add vue-cropper

代碼拷貝
廢話不多說,代碼也不多敲,相信大家和我一樣,能粘貼絕不手敲,哈哈。

組件封裝CropperImage.vue

<template>
  <div class="cropper-content">
    <div class="cropper-box">
      <div class="cropper">
        <vue-cropper
            ref="cropper"
            :img="option.img"
            :outputSize="option.outputSize"
            :outputType="option.outputType"
            :info="option.info"
            :canScale="option.canScale"
            :autoCrop="option.autoCrop"
            :autoCropWidth="option.autoCropWidth"
            :autoCropHeight="option.autoCropHeight"
            :fixed="option.fixed"
            :fixedNumber="option.fixedNumber"
            :full="option.full"
            :fixedBox="option.fixedBox"
            :canMove="option.canMove"
            :canMoveBox="option.canMoveBox"
            :original="option.original"
            :centerBox="option.centerBox"
            :height="option.height"
            :infoTrue="option.infoTrue"
            :maxImgSize="option.maxImgSize"
            :enlarge="option.enlarge"
            :mode="option.mode"
            @realTime="realTime"
            @imgLoad="imgLoad">
        </vue-cropper>
      </div>
      <!--底部操作工具按鈕-->
      <div class="footer-btn">
        <div class="scope-btn">
          <label class="btn" for="uploads">選擇封面</label>
          <input type="file" id="uploads" style="position:absolute; clip:rect(0 0 0 0);" accept="image/png, image/jpeg, image/gif, image/jpg" @change="selectImg($event)">
          <el-button size="mini" type="danger" plain icon="el-icon-zoom-in" @click="changeScale(1)">放大</el-button>
          <el-button size="mini" type="danger" plain icon="el-icon-zoom-out" @click="changeScale(-1)">縮小</el-button>
          <el-button size="mini" type="danger" plain @click="rotateLeft">? 左旋轉(zhuǎn)</el-button>
          <el-button size="mini" type="danger" plain @click="rotateRight">? 右旋轉(zhuǎn)</el-button>
        </div>
        <div class="upload-btn">
          <el-button size="mini" type="success" @click="uploadImg('blob')">上傳封面 <i class="el-icon-upload"></i></el-button>
        </div>
      </div>
    </div>
    <!--預(yù)覽效果圖-->
    <div class="show-preview">
      <div :style="previews.div" class="preview">
        <img :src="previews.url" :style="previews.img">
      </div>
    </div>
  </div>
</template>

<script>
import { VueCropper } from 'vue-cropper'
export default {
  name: "CropperImage",
  components: {
    VueCropper
  },
  props:['Name'],
  data() {
    return {
      name:this.Name,
      previews: {},
      option:{
        img: '',             //裁剪圖片的地址
        outputSize: 1,       //裁剪生成圖片的質(zhì)量(可選0.1 - 1)
        outputType: 'jpeg',  //裁剪生成圖片的格式(jpeg || png || webp)
        info: true,          //圖片大小信息
        canScale: true,      //圖片是否允許滾輪縮放
        autoCrop: true,      //是否默認(rèn)生成截圖框
        autoCropWidth: 230,  //默認(rèn)生成截圖框?qū)挾?        autoCropHeight: 150, //默認(rèn)生成截圖框高度
        fixed: true,         //是否開啟截圖框?qū)捀吖潭ū壤?        fixedNumber: [1.53, 1], //截圖框的寬高比例
        full: false,         //false按原比例裁切圖片,不失真
        fixedBox: true,      //固定截圖框大小,不允許改變
        canMove: false,      //上傳圖片是否可以移動(dòng)
        canMoveBox: true,    //截圖框能否拖動(dòng)
        original: false,     //上傳圖片按照原始比例渲染
        centerBox: false,    //截圖框是否被限制在圖片里面
        height: true,        //是否按照設(shè)備的dpr 輸出等比例圖片
        infoTrue: false,     //true為展示真實(shí)輸出圖片寬高,false展示看到的截圖框?qū)捀?        maxImgSize: 3000,    //限制圖片最大寬度和高度
        enlarge: 1,          //圖片根據(jù)截圖框輸出比例倍數(shù)
        mode: '230px 150px'  //圖片默認(rèn)渲染方式
      }
    };
  },
  methods: {
    //初始化函數(shù)
    imgLoad (msg) {
      console.log("工具初始化函數(shù)====="+msg)
    },
    //圖片縮放
    changeScale (num) {
      num = num || 1
      this.$refs.cropper.changeScale(num)
    },
    //向左旋轉(zhuǎn)
    rotateLeft () {
      this.$refs.cropper.rotateLeft()
    },
    //向右旋轉(zhuǎn)
    rotateRight () {
      this.$refs.cropper.rotateRight()
    },
    //實(shí)時(shí)預(yù)覽函數(shù)
    realTime (data) {
      this.previews = data
    },
    //選擇圖片
    selectImg (e) {
      let file = e.target.files[0]
      if (!/\.(jpg|jpeg|png|JPG|PNG)$/.test(e.target.value)) {
        this.$message({
          message: '圖片類型要求:jpeg、jpg、png',
          type: "error"
        });
        return false
      }
      //轉(zhuǎn)化為blob
      let reader = new FileReader()
      reader.onload = (e) => {
        let data
        if (typeof e.target.result === 'object') {
          data = window.URL.createObjectURL(new Blob([e.target.result]))
        } else {
          data = e.target.result
        }
        this.option.img = data
      }
      //轉(zhuǎn)化為base64
      reader.readAsDataURL(file)
    },
    //上傳圖片
    uploadImg (type) {
      let _this = this;
      if (type === 'blob') {
        //獲取截圖的blob數(shù)據(jù)
        this.$refs.cropper.getCropBlob(async (data) => {
          let formData = new FormData();
          formData.append('file',data,"DX.jpg")
          //調(diào)用axios上傳
          let {data: res} = await _this.$http.post('/api/file/imgUpload', formData)
          if(res.code === 200){
            _this.$message({
              message: res.msg,
              type: "success"
            });
            let data = res.data.replace('[','').replace(']','').split(',');
            let imgInfo = {
              name : _this.Name,
              url : data[0]
            };
            _this.$emit('uploadImgSuccess',imgInfo);
          }else {
            _this.$message({
              message: '文件服務(wù)異常,請(qǐng)聯(lián)系管理員!',
              type: "error"
            });
          }
        })
      }
    },
  },
}
</script>

<style scoped lang="scss">
.cropper-content{
  display: flex;
  display: -webkit-flex;
  justify-content: flex-end;
  .cropper-box{
    flex: 1;
    width: 100%;
    .cropper{
      width: auto;
      height: 300px;
    }
  }

  .show-preview{
    flex: 1;
    -webkit-flex: 1;
    display: flex;
    display: -webkit-flex;
    justify-content: center;
    .preview{
      overflow: hidden;
      border:1px solid #67c23a;
      background: #cccccc;
    }
  }
}
.footer-btn{
  margin-top: 30px;
  display: flex;
  display: -webkit-flex;
  justify-content: flex-end;
  .scope-btn{
    display: flex;
    display: -webkit-flex;
    justify-content: space-between;
    padding-right: 10px;
  }
  .upload-btn{
    flex: 1;
    -webkit-flex: 1;
    display: flex;
    display: -webkit-flex;
    justify-content: center;
  }
  .btn {
    outline: none;
    display: inline-block;
    line-height: 1;
    white-space: nowrap;
    cursor: pointer;
    -webkit-appearance: none;
    text-align: center;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    outline: 0;
    -webkit-transition: .1s;
    transition: .1s;
    font-weight: 500;
    padding: 8px 15px;
    font-size: 12px;
    border-radius: 3px;
    color: #fff;
    background-color: #409EFF;
    border-color: #409EFF;
    margin-right: 10px;
  }
}
</style>


注意:裁剪組件的基礎(chǔ)配置option,小編這里配置了官方所給的所有基礎(chǔ)配置,大家可以按需配置。

新建Tailoring.vue 調(diào)用封裝好的組件:

這里我們先簡(jiǎn)單說一下思路,通過按鈕觸發(fā)事件打開我們的剪裁窗口,選擇圖片,點(diǎn)擊上傳之后,將地址回調(diào)回來,拿到地址就可以處理我們的業(yè)務(wù)了,比如隨著表單一起將回調(diào)地址存入數(shù)據(jù)庫(kù)等等。

Tailoring.vue:

<template>
  <div class="cropper-app">
    <el-form :model="formValidate" :rules="ruleValidate" ref="formValidate" label-width="100px" class="demo-ruleForm">
      <el-form-item label="封面上傳" prop="mainImage">
        <div class="list-img-box">
          <div v-if="formValidate.mainImage !== ''">
            <img :src="formValidate.mainImage" style='width:300px;height:150px' alt="自定義封面">
          </div>
          <div v-else class="upload-btn" style="height: 120px;" @click="uploadPicture('flagImg')">
            <i class="el-icon-plus" style="font-size: 30px;"></i>
            <span>封面設(shè)置</span>
          </div>
        </div>
        <input type="hidden" v-model="formValidate.mainImage" placeholder="請(qǐng)?zhí)砑臃饷?>
      </el-form-item>
    </el-form>
    <!-- 剪裁組件彈窗 -->
    <el-dialog
        title="裁切封面"
        :visible.sync="cropperModel"
        width="950px"
        center
       >
     <cropper-image
         :Name="cropperName"
         @uploadImgSuccess = "handleUploadSuccess"
         ref="child">
     </cropper-image>
    </el-dialog>
    <!--查看大封面-->
    <el-dialog
        title="查看大封面"
        :visible.sync="imgVisible"
        center>
      <img :src="imgName" v-if="imgVisible" style="width: 100%" alt="查看">
    </el-dialog>
  </div>
</template>

<script>
import CropperImage from "@/views/resmanage/CropperImage";
export default {
  name: "Tailoring",
  components: {CropperImage},
  data () {
    return {
      formValidate: {
        mainImage: '',
      },
      ruleValidate: {
        mainImage: [
          {required: true, message: '請(qǐng)上傳封面', trigger: 'blur'}
        ],
      },
      //裁切圖片參數(shù)
      cropperModel:false,
      cropperName:'',
      imgName: '',
      imgVisible: false
    }
  },
  methods: {
    //封面設(shè)置
    uploadPicture(name){
      this.cropperName = name;
      this.cropperModel = true;
    },
    //圖片上傳成功后
    handleUploadSuccess (data){
      console.log(data)
      switch(data.name){
        case 'flagImg':
          this.formValidate.mainImage = 'http://ydfblog.cn/dfs/'+data.url;
          console.log('最終輸出'+data.name)
          break;
      }
      this.cropperModel = false;
    }
  }
}
</script>
<style scoped>
  .upload-list-cover{
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
      padding: 0 40px;
      align-items: center;
      background: rgba(0,0,0,.6);
      opacity: 0;
      transition: opacity 1s;
  }
  .cover_icon {
    font-size: 30px;
  }
  .upload-btn{
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -ms-flex-wrap: wrap;
    flex-wrap: wrap;
    -webkit-box-pack: center;
    -ms-flex-pack: center;
    justify-content: center;
    -webkit-box-align: center;
    -ms-flex-align: center;
    align-items: center;
    border: 1px solid #cccccc;
    border-radius: 5px;
    overflow: hidden;
    box-shadow: 0 0 1px #cccccc;
  }
  .upload-btn:hover {
    border: 1px solid #69b7ed;
  }
  .upload-btn i{
    margin: 5px;
  }
</style>

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容