Vue圖片裁剪功能實現代碼

一、效果展示:

1、表單的圖片上傳項:

– 新增時默認一個空白Input框

– 更新時展示以往上傳存放的圖片,

  - 點擊【查看】瀏覽完整大小

  - 點擊【刪除】清空src地址,重新上傳新照片

2、裁剪框頁面

– 先選擇裁剪的圖片

– 右側展示裁剪區域

– 支持放大縮小,圖片旋轉

– 點擊【上傳圖片】調用後臺上傳接口進行上傳

二、代碼部分

1、首先安裝Vue-Cropper,基於此組件的基礎上開發的裁剪頁面

npm install vue-cropper
"vue-cropper": "^0.5.8"

2、裁剪彈窗的組件編寫:

<template>
  <div
    v-loading="loading"
    class="cropper-content"
  >
    <div class="cropper-box">
      <div class="cropper">
        <vue-cropper
          ref="cropper"
          :img="option.img"
          :output-size="option.outputSize"
          :output-type="option.outputType"
          :info="option.info"
          :can-scale="option.canScale"
          :auto-crop="option.autoCrop"
          :auto-crop-width="autoCropWidth"
          :auto-crop-height="autoCropHeight"
          :fixed="option.fixed"
          :fixed-number="option.fixedNumber"
          :full="option.full"
          :fixed-box="option.fixedBox"
          :can-move="option.canMove"
          :can-move-box="option.canMoveBox"
          :original="option.original"
          :center-box="option.centerBox"
          :height="option.height"
          :info-true="option.infoTrue"
          :max-img-size="option.maxImgSize"
          :enlarge="option.enlarge"
          :mode="option.mode"
          @realTime="realTime"
          @imgLoad="imgLoad"
        />
      </div>
      <!--底部操作工具按鈕-->
      <div class="footer-btn">
        <div class="scope-btn">
          <label
            class="btn"
            for="uploads"
          >選擇圖片</label>
          <input
            id="uploads"
            type="file"
            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"
          >↺ 左旋轉</el-button>
          <el-button
            size="mini"
            type="danger"
            plain
            @click="rotateRight"
          >↻ 右旋轉</el-button>
        </div>
        <div class="upload-btn">
          <el-button
            size="mini"
            type="success"
            @click="uploadImg('blob')"
          >上傳圖片<i class="el-icon-upload" /></el-button>
        </div>
      </div>
    </div>
    <!--預覽效果圖-->
    <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'
import { uploadFile } from '@/api/smrz/setting'
import { regularFileName } from '@/utils'
export default {
  name: 'CropperImage',
  components: {
    VueCropper
  },
  /*  props: ['name2'],*/
  props: {
    autoCropWidth: { // 默認生成截圖框寬度
      type: Number,
      default: 410
    },
    autoCropHeight: { // 默認生成截圖框高度
      type: Number,
      default: 150
    },
    busType: {
      type: String,
      default: 'advertPic'
    }
  },
  data() {
    return {
      loading: false,
      name: this.Name,
      previews: {},
      option: {
        img: '', // 裁剪圖片的地址
        outputSize: 1, // 裁剪生成圖片的質量(可選0.1 - 1)
        outputType: 'jpeg', // 裁剪生成圖片的格式(jpeg || png || webp)
        info: true, // 圖片大小信息
        canScale: true, // 圖片是否允許滾輪縮放
        autoCrop: true, // 是否默認生成截圖框
        // autoCropWidth: 410, 默認生成截圖框寬度
        // autoCropHeight: 150,  默認生成截圖框高度
        fixed: false, // 是否開啟截圖框寬高固定比例
        fixedNumber: [1.53, 1], // 截圖框的寬高比例
        full: true, // false按原比例裁切圖片,不失真
        fixedBox: true, // 固定截圖框大小,不允許改變
        canMove: true, // 上傳圖片是否可以移動
        canMoveBox: true, // 截圖框能否拖動
        original: true, // 上傳圖片按照原始比例渲染
        centerBox: false, // 截圖框是否被限制在圖片裡面
        height: true, // 是否按照設備的dpr 輸出等比例圖片
        infoTrue: false, // true為展示真實輸出圖片寬高,false展示看到的截圖框寬高
        maxImgSize: 3000, // 限制圖片最大寬度和高度
        enlarge: 1, // 圖片根據截圖框輸出比例倍數
        mode: '230px 150px' // 圖片默認渲染方式
      },
      randomFileName: ''
    }
  },
  methods: {
    // 初始化函數
    imgLoad(msg) {
      console.log('工具初始化函數=====' + msg)
    },
    // 圖片縮放
    changeScale(num) {
      num = num || 1
      this.$refs.cropper.changeScale(num)
    },
    // 向左旋轉
    rotateLeft() {
      this.$refs.cropper.rotateLeft()
    },
    // 向右旋轉
    rotateRight() {
      this.$refs.cropper.rotateRight()
    },
    // 實時預覽函數
    realTime(data) {
      this.previews = data
    },
    // 選擇圖片
    selectImg(e) {
      const 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
      }
      // 轉化為blob
      const 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
      }
 
      console.log(`file.name => ${file.name}`)
      // 轉化為base64
      reader.readAsDataURL(file)
    },
    // 上傳圖片
    uploadImg(type) {
      const _this = this
      if (type === 'blob') {
        // 獲取截圖的blob數據
        this.$refs.cropper.getCropBlob(async(data) => {
          _this.loading = true
          const formData = new FormData()
          // formData.append('file', data, this.createNewFileName())
          // if (this.autoCropWidth === 100) {
          //   formData.append('subDir', 'exchange')
          // } else if (this.autoCropHeight === 80) {
          //   formData.append('subDir', 'task')
          // } else {
          //   formData.append('subDir', 'rotate')
          // }
 
          _this.randomFileName = this.createNewFileName()
 
          // 給blob對象的filename屬性賦值文件名
          formData.append('rpc', data, _this.randomFileName)
          // 給參數賦值文件名
          formData.append('fileName', _this.randomFileName)
          formData.append('busType', _this.busType)
 
          /* this.fileName = data.file.name
          formData.append('fileName', this.fileName)*/
          // 調用axios上傳
          /* const { data: res } = await _this.$http.post('/api/file/imgUpload', formData)*/
 
          uploadFile(formData).then(res => {
            /* this.handleSuccess(res)*/
            if (res.code === 200) {
              _this.$message({
                message: '圖片上傳成功',
                type: 'success'
              })
              // const data = res.data.replace('[', '').replace(']', '').split(',')
 
              // const imgInfo = {
              //   name: 'DX.jpg',
              //   url: res.data.agentUrl,
              //   storeUrl: res.data.storeUrl,
              //   uploadResult: res.data.uploadResult
              // }
              // _this.$emit('uploadImgSuccess', imgInfo)
 
              // 添加隨機生成的文件名
              res.fileName = _this.randomFileName
 
              _this.$emit('uploadImgSuccess', res)
            } else {
              _this.$message({
                message: '文件服務異常,請聯系管理員!',
                type: 'error'
              })
            }
          }).finally(() => {
            _this.loading = false
          })
        })
 
        /*  if (flag) {
            this.$message.warning('請選擇圖片')
          }*/
      }
    },
    createNewFileName() {
      // const now = Date.now()
      // const fileName = now + '-' + Math.ceil(Math.random() * 100)
      // return fileName + '.jpg'
      const fileName = regularFileName()
      return fileName + '.jpg'
    }
  }
}
</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: 0.1s;
    transition: 0.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>

需要更改成自己的上傳接口:

import { uploadFile } from '@/api/smrz/setting'

後臺接口參數如下,要求表單方式上傳

/**
  * 上傳附件
  *
  * @param file     文件流(註意帶文件後綴,統一使用.jpg結尾)
  * @param fileName 文件名稱(唯一性)
  * @param busType  業務類型(具體值參考ApiConstants類中FILE_開頭常量說明)
  * @author wangkun
  * @createTime 2022/7/19 17:18
  */
 @PostMapping(value = "/file/upload", consumes = "multipart/form-data")
 public RpcResult uploadFile(@RequestParam(value = "rpc") MultipartFile file, @RequestParam(value = "fileName") String fileName, @RequestParam(value = "busType") String busType) {

在uploadImg函數這裡,使用FormData對象包裝請求參數

註意append方法,要給文件對象指定文件名,必須要入參第三個參數

否則默認名稱blob

按實際接口對應調整參數即可

const formData = new FormData()
 
_this.randomFileName = this.createNewFileName()
 
// 給blob對象的filename屬性賦值文件名
formData.append('rpc', data, _this.randomFileName)
// 給參數賦值文件名
formData.append('fileName', _this.randomFileName)
formData.append('busType', _this.busType)
 
uploadFile(formData)

其它自定義參數,通過Props屬性傳入此組件

props: {
  autoCropWidth: { // 默認生成截圖框寬度
    type: Number,
    default: 410
  },
  autoCropHeight: { // 默認生成截圖框高度
    type: Number,
    default: 150
  },
  busType: {
    type: String,
    default: 'advertPic'
  }
},

文件名的生成方法,就是當前時間按單位數值排序

實際使用根據業務實際情況改寫

export function regularFileName() {
  const now = new Date()
  const year = now.getFullYear()
  const month = digitFix(now.getMonth() + 1)
  const dayOfMonth = digitFix(now.getDate())
  const hour = digitFix(now.getHours())
  const minute = digitFix(now.getMinutes())
  const second = digitFix(now.getSeconds())
  const millSecond = now.getMilliseconds()
  return `${year}${month}${dayOfMonth}${hour}${minute}${second}${millSecond}`
}const fileName = `${regularFileName()}

3、【圖片上傳表單項】組件編寫

<template>
  <div class="cropper-app">
    <el-form
      ref="ruleForm"
      :model="formValidate"
      :rules="ruleValidate"
      label-width="110px"
      class="demo-ruleForm"
    >
      <el-form-item
        :label="label"
        prop="mainImage"
      >
        <div class="list-img-box">
          <div
            v-if="formValidate.mainImage !== ''"
            class="img_div"
            style="height: 100px;"
          >
            <img
              :src="formValidate.mainImage"
              alt="圖片找不到"
            >
            <a href="#" rel="external nofollow" >
              <div class="mask">
                <h3 style="">
                  <i
                    class="el-icon-zoom-in"
                    @click="clickImg('zoom-in')"
                  />
                    
                  <i
                    class="el-icon-delete"
                    @click="clickImg('delete')"
                  />
                </h3>
              </div>
            </a>
          </div>
          <div
            v-else
            class="upload-btn"
            style="height: 100px;width: 200px"
            @click="uploadPicture('flagImg')"
          >
            <i
              class="el-icon-plus"
              style="font-size: 30px;"
            />
            <!--<span>封面設置</span>-->
          </div>
        </div>
        <input
          v-model="formValidate.mainImage"
          type="hidden"
          placeholder="請添加封面"
        >
      </el-form-item>
    </el-form>
    <!-- 剪裁組件彈窗 -->
    <el-dialog
      v-if="cropperModel"
      title="圖片剪切"
      :visible.sync="cropperModel"
      width="1020px"
      center
      append-to-body
    >
      <cropper-image
        v-if="cropperModel"
        ref="child"
        :auto-crop-width="autoCropWidth"
        :auto-crop-height="autoCropHeight"
        :bus-type="busType"
        @uploadImgSuccess="handleUploadSuccess"
      />
    </el-dialog>
    <!--查看大封面-->
    <el-dialog
      title=""
      :visible.sync="imgVisible"
      center
      append-to-body
    >
      <img
        v-if="imgVisible"
        :src="imgUrl"
        style="width: 100%"
        alt="查看"
      >
    </el-dialog>
  </div>
</template>
 
<script>
import CropperImage from '@/components/CropperImage'
import { commonsDownloadAPI } from '@/api/smrz/setting'
export default {
  name: 'Tailoring',
  components: { CropperImage },
  props: {
    label: {
      type: String,
      default: '上傳圖片'
    },
    url: {
      type: String
    },
    autoCropWidth: { // 默認生成截圖框寬度
      type: Number,
      default: 410
    },
    autoCropHeight: { // 默認生成截圖框高度
      type: Number,
      default: 150
    },
    isSignFlag: {
      type: Boolean,
      default: false
    },
    busType: {
      type: String,
      default: 'busType'
    }
  },
 
  data() {
    var imageUrl2 = (rule, value, callback) => {
      if (!this.isSignFlag) {
        return callback()
      }
      if (!value) {
        return callback(new Error('請輸上傳圖片'))
      }
      return callback()
    }
    return {
      formValidate: {
        mainImage: ''
      },
      ruleValidate: {
        mainImage: [
          /*   { required: true, message: '請上傳圖片', trigger: 'blur' }*/
          { required: true, validator: imageUrl2, trigger: 'blur' }
        ]
      },
      // 裁切圖片參數
      cropperModel: false,
      cropperName: '',
      imgUrl: '',
      imgVisible: false,
 
      dialogImageUrl: '',
      dialogVisible: false
    }
  },
  created() {
    this.formValidate.mainImage = this.url
    this.imgUrl = this.url
  },
  methods: {
    validateForm() {
      this.$refs['ruleForm'].validate((valid) => {
        this.$emit('validVal', valid)
      })
    },
    // 封面設置
    uploadPicture(name) {
      this.cropperName = name
      this.cropperModel = true
    },
    // 圖片上傳成功後
    async handleUploadSuccess(data) {
      // this.formValidate.mainImage = data.url
 
      // 圖片回顯
      const { data: res2, code } = await commonsDownloadAPI({
        fileName: data.fileName,
        busType: 'advertPic'
      })
 
      const imgBase64 =
        code !== 200
          ? '-1' : `data:image/jpeg;base64,${res2.data}`
      this.formValidate.mainImage = imgBase64
 
      /* switch (data.name) {
        case 'flagImg':
          this.formValidate.mainImage = data.url
          console.log('最終輸出' + data.name)
          console.log('最終輸出2' + this.formValidate)
          break
      }*/
      this.cropperModel = false
      this.$emit('uploadSuccess', data)
    },
    clickImg(val) {
      if (val === 'delete') {
        this.formValidate.mainImage = ''
        this.$emit('deleteImage')
      } else if (val === 'zoom-in') {
        //
        this.imgUrl = this.formValidate.mainImage
        this.imgVisible = true
      }
    }
 
  }
}
</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, 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;
}
 
.img_div img {
  width: 200px !important;
  height: 100px !important;
  /*  margin: 20px 400px 0 400px;
    position: relative;
    width: 531px;
    height: 354px;*/
}
.mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 200px;
  height: 100px;
  background: rgba(101, 101, 101, 0.6);
  color: #ffffff;
  opacity: 0;
}
.mask h3 {
  text-align: center;
  line-height: 60px;
}
 
.img_div a:hover .mask {
  opacity: 0.8;
}
</style>

表單項組件需要引入

1、裁剪組件

2、圖片下載接口

import CropperImage from '@/components/CropperImage'
import { commonsDownloadAPI } from '@/api/smrz/setting'

3、表單項設置瞭自定義校驗

var imageUrl2 = (rule, value, callback) => {
  if (!this.isSignFlag) {
    return callback()
  }
  if (!value) {
    return callback(new Error('請輸上傳圖片'))
  }
  return callback()
}

就是檢查src有沒有地址或者base64資源,校驗觸發的效果:

4、圖片上傳後的回調處理:

上傳成功後,回到表單頁需要立即回顯之前上傳的圖片

所以需要調用圖片下載接口來獲取剛剛上傳的資源,

在這個回調方法中實現,因為下載接口提供的資源不是圖片地址,而是返回Base64編碼

這裡我寫的是base64編碼資源的回顯處理

實際使用根據業務實際情況改寫

// 圖片上傳成功後
async handleUploadSuccess(data) {
  // this.formValidate.mainImage = data.url
 
  // 圖片回顯
  const { data: res2, code } = await commonsDownloadAPI({
    fileName: data.fileName,
    busType: 'advertPic'
  })
 
  const imgBase64 =
    code !== 200
      ? '-1' : `data:image/jpeg;base64,${res2.data}`
  this.formValidate.mainImage = imgBase64
 
  /* switch (data.name) {
    case 'flagImg':
      this.formValidate.mainImage = data.url
      console.log('最終輸出' + data.name)
      console.log('最終輸出2' + this.formValidate)
      break
  }*/
  this.cropperModel = false
  this.$emit('uploadSuccess', data)
},

4、業務功能引用

引入表單項

import Tailoring from '@/components/Tailoring'

聲明組件,並註入參數

<div class="ant-upload-preview">
  <tailoring
    v-if="true"
    ref="child"
    label="廣告圖片"
    :is-sign-flag="true"
    :url="url"
    :bus-type="businessType"
    :auto-crop-height="80"
    :auto-crop-width="410"
    @uploadSuccess="uploadSuccess"
    @validVal="validVal"
  />
</div>

– url是一開始加載組件需要回顯的圖片資源地址  

– isSignFlag變量用來輔助自定義校驗的,為false時直接放行校驗,所以默認寫死true

– bus-type是自定義的業務參數

– auto-crop的寬高用來配置裁剪的寬高,預覽大小和裁剪大小合並使用這兩個參數

上傳成功的回調,uploadSuccess,可以在組件自定義需要的參數

這裡是以圖片名稱作為記錄主鍵,所以要傳入這個文件名

實際使用根據業務實際情況改寫

async uploadSuccess(res) {
  console.log(`上傳結果 res -> ${JSON.stringify(res)}`)
  const fileName = res.fileName
  this.newId = fileName.substring(0, fileName.lastIndexOf('.'))
},

校驗值,應該是返回校驗後的src值,但我這裡沒用上,所以不執行任何邏輯

validVal(val) {},

要觸發【裁剪表單項】校驗,使用

this.$refs.child.validateForm()

到此這篇關於Vue圖片裁剪功能支持的文章就介紹到這瞭,更多相關vue圖片裁剪內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: