首頁 > 軟體

Vue圖片裁剪功能實現程式碼

2022-08-24 14:01:38

一、效果展示:

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圖片裁剪內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com