vue2 结合 elementui 实现图片裁剪上传

发布于:2024-04-26 ⋅ 阅读:(22) ⋅ 点赞:(0)

1、效果

vue 实现图片裁剪上传

2、准备

第三方库:vue-cropper - npm

npm i vue-cropper

3、封装组件

<template>
  <div class="cropper-wrapper">
    <!-- element 上传图片按钮 -->
    <template v-if="!isPreview">
      <el-upload
        ref="upload"
        class="upload-demo"
        :action="actionUrl"
        drag
        :on-change="handleChangeUpload"
        :auto-upload="false"
        :show-file-list="false"
        :disabled="disabled"
      >
        <i class="el-icon-plus upload-demo-icon"></i>
      </el-upload>
    </template>
    <div v-else class="pre-box">
      <el-upload
        class="upload-demo"
        action=""
        :auto-upload="false"
        :show-file-list="false"
        :on-change="handleChangeUpload"
        :disabled="disabled"
      >
        <img :src="previewImg" alt="裁剪图片" style="width: 100px;height: 100px" />
      </el-upload>
    </div>
    <!-- vueCropper 剪裁图片实现-->
    <el-dialog
      title="图片剪裁"
      :visible.sync="dialogVisible"
      class="crop-dialog"
      append-to-body
    >
      <div class="cropper-content">
        <div class="cropper" style="text-align: center">
          <VueCropper
            ref="cropper"
            :img="option.img"
            :output-size="option.size"
            :output-type="option.outputType"
            :info="true"
            :full="option.full"
            :can-move="option.canMove"
            :can-move-box="option.canMoveBox"
            :original="option.original"
            :auto-crop="option.autoCrop"
            :fixed="option.fixed"
            :fixed-number="option.fixedNumber"
            :center-box="option.centerBox"
            :info-true="option.infoTrue"
            :fixed-box="option.fixedBox"
            :auto-crop-width="option.autoCropWidth"
            :auto-crop-height="option.autoCropHeight"
            @cropMoving="cropMoving"
          />
        </div>
      </div>
      <div class="action-box">
        <el-upload
          class="upload-demo"
          action=""
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handleChangeUpload"
        >
          <el-button type="primary">更换图片</el-button>
        </el-upload>
        <!-- <el-button type="primary" @click="clearImgHandle">
          清除图片
        </el-button> -->
        <el-button type="primary" @click="rotateLeftHandle">
          左旋转
        </el-button>
        <el-button type="primary" @click="rotateRightHandle">
          右旋转
        </el-button>
        <!-- <el-button type="primary" plain @click="changeScaleHandle(1)">
          放大
        </el-button>
        <el-button type="primary" plain @click="changeScaleHandle(-1)">
          缩小
        </el-button> -->
        <el-button type="primary" @click="option.fixed = !option.fixed">
          {{ option.fixed ? '固定比例' : '自由比例' }}
        </el-button>
        <el-button type="primary" @click="downloadHandle('blob')">
          下载
        </el-button>
      </div>
      <div style="height: 30px"></div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="loading" @click="finish">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { VueCropper }  from 'vue-cropper'
import { uploadImage } from '@/api/bff'
export default {
  name: 'Cropper',
  components: {
    VueCropper,
  },
  model: {
    prop: 'value',
    event: 'input'
  },
  props: {
    value: {
      type: String,
      default: ''
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      actionUrl: process.env.VUE_APP_UPLOAD_API + '/api/v1.0/oss/upload',
      isPreview: false,
      dialogVisible: false,
      previewImg: '', // 预览图片地址
      // 裁剪组件的基础配置option
      option: {
        img: '', // 裁剪图片的地址
        info: true, // 裁剪框的大小信息
        outputSize: 1, // 裁剪生成图片的质量
        outputType: 'png', // 裁剪生成图片的格式
        canScale: true, // 图片是否允许滚轮缩放
        autoCrop: true, // 是否默认生成截图框
        canMoveBox: true, // 截图框能否拖动
        autoCropWidth: 200, // 默认生成截图框宽度
        autoCropHeight: 200, // 默认生成截图框高度
        fixedBox: false, // 固定截图框大小 不允许改变
        fixed: false, // 是否开启截图框宽高固定比例
        fixedNumber: [1, 1], // 截图框的宽高比例
        full: false, // 是否输出原图比例的截图
        original: false, // 上传图片按照原始比例渲染
        centerBox: true, // 截图框是否被限制在图片里面
        infoTrue: true, // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
      },
      // 防止重复提交
      loading: false,
    };
  },
  watch: {
    value: {
      handler(val, newval) {
        if (val !== newval && val) {
          this.isPreview = true;
          this.previewImg = val
        }
      },
      immediate: true
    }
  },
  methods: {
    // 上传按钮 限制图片大小和类型
    handleChangeUpload(file) {
      const isJPG =
        file.raw.type === 'image/jpeg' || file.raw.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
        return false;
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
        return false;
      }
      // 上传成功后将图片地址赋值给裁剪框显示图片
      this.$nextTick(async () => {
        // base64方式
        // this.option.img = await fileByBase64(file.raw)
        this.option.img = URL.createObjectURL(file.raw);
        this.loading = false;
        this.dialogVisible = true;
      });
    },
    // 放大/缩小
    changeScaleHandle(num) {
      num = num || 1;
      this.$refs.cropper.changeScale(num);
    },
    // 左旋转
    rotateLeftHandle() {
      this.$refs.cropper.rotateLeft();
    },
    // 右旋转
    rotateRightHandle() {
      this.$refs.cropper.rotateRight();
    },
    // 下载
    downloadHandle(type) {
      let aLink = document.createElement('a');
      aLink.download = 'author-img';
      if (type === 'blob') {
        this.$refs.cropper.getCropBlob((data) => {
          aLink.href = URL.createObjectURL(data);
          aLink.click();
        });
      } else {
        this.$refs.cropper.getCropData((data) => {
          aLink.href = data;
          aLink.click();
        });
      }
    },
    // 清理图片
    clearImgHandle() {
      this.option.img = '';
    },
    // 截图框移动回调函数
    cropMoving() {
      // 截图框的左上角 x,y和右下角坐标x,y
      // let cropAxis = [data.axis.x1, data.axis.y1, data.axis.x2, data.axis.y2]
      // console.log(cropAxis)
    },
    finish() {
      // 获取截图的 blob 数据
      this.$refs.cropper.getCropBlob((blob) => {
        this.loading = true;
        this.dialogVisible = false;
        this.previewImg = URL.createObjectURL(blob);
        this.isPreview = true;
        // this.$refs.submit()
        this.uploadImage(blob)
      });
      // 获取截图的 base64 数据
      // this.$refs.cropper.getCropData(data => {
      //     console.log(data)
      // })
    },
    uploadImage(blob) {
      let file = new File([blob], new Date() + '图片.png', { type: 'image/png', lastModified: Date.now() });
      file.uid = Date.now();
      var fd = new FormData();
      fd.append("file", file, new Date() + "图片.png");
      fd.append("project", "micropark_coordination");

      uploadImage(fd).then(res => {
        console.log('图片上传', res)
        if (res.Type === 200) {
          const imageUrl = res.Data.HostSetting.External + res.Data.PathSetting.Path;
          this.$emit('input', imageUrl);
        }
      });
    }
  },
};
</script>

<style lang="scss" scoped>
:deep(.el-upload-dragger) {
  width: 100px !important;
  height: 100px !important;
}
.cropper-wrapper {
  width: 100%;
  height: 100%;
  .upload-demo .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .upload-demo .el-upload:hover {
    border-color: #409eff;
  }
  .upload-demo-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  .pre-box {
    display: flex;
    flex-direction: column;
    align-items: center;
    button {
      width: 100px;
      margin-top: 15px;
    }
  }
}

.crop-dialog {
  .cropper-content {
    padding: 0 40px;

    .cropper {
      width: auto;
      height: 350px;
    }
  }

  .action-box {
    padding: 25px 40px 0 40px;
    display: flex;
    justify-content: center;

    button {
      width: 80px;
      margin-right: 15px;
    }
  }

  .dialog-footer {
    button {
      width: 100px;
    }
  }
}
</style>

4、使用

<upload-picture-cropper v-model="info.UserExternalIdentify.WeChatQrCode" :disabled="isDisable" />