vue-cropper插件实现图片截取上传组件封装


Posted in Vue.js onMay 27, 2021

基于vue-cropper插件实现图片截取上传组件封装的具体代码,供大家参考,具体内容如下

需求场景:

后台开发需要上传图片并进行相应比例尺寸图片的截取,本组件开发采用Ant Design Vue组件库搭配vue-cropper插件进行封装

实现如下

vue-cropper插件实现图片截取上传组件封装

vue-cropper插件实现图片截取上传组件封装

html

<template>
  <div>
    <a-upload
      name="avatar"
      list-type="picture-card"
      class="avatar-uploader"
      :show-upload-list="false"
      :custom-request="customRequest"
      :before-upload="beforeUpload"
      :style="`width: ${width}; height: ${height};`"
    >
      <img
        v-if="imageUrl && !loading"
        :src="imageUrl"
        alt="avatar"
        :style="`width: ${width}; height: ${height};`"
      />
      <div v-else>
        <a-icon :type="loading ? 'loading' : 'plus'" />
        <div class="ant-upload-text">上传图片</div>
      </div>
    </a-upload>
    <a-modal
      v-model="imageCut.isShowModal"
      title="图片截取"
      width="400px"
      @ok="finish"
      @cancel="imageCut.close"
    >
      <div class="cropper-content" v-if="imageCut.isShowModal">
        <div class="cropper" style="text-align:center">
          <vueCropper
            ref="cropper"
            :img="imageCut.imgFile"
            :outputSize="outputSize"
            :outputType="outputType"
            :info="info"
            :full="full"
            :canMove="canMove"
            :canMoveBox="canMoveBox"
            :original="original"
            :autoCrop="autoCrop"
            :fixed="fixed"
            :fixedNumber="fixedNumber"
            :centerBox="centerBox"
            :infoTrue="infoTrue"
            :fixedBox="fixedBox"
          ></vueCropper>
        </div>
      </div>
    </a-modal>
  </div>
</template>

js

<script>
import { uploadImage } from '@/api/common'
import { VueCropper } from "vue-cropper";
export default {
  name: 'ImageUpload',
  components: { VueCropper },
  data() {
    return {
      loading: false,
      imageCut: {
        isShowModal: false,
        imgFile: '',
        init: imgFile => {
          this.imageCut.imgFile = imgFile
          this.imageCut.isShowModal = true
        },
        close: () => {
          this.imageCut.imgFile = ''
          this.imageCut.isShowModal = false
        }
      }
    }
  },
  props: {
    imageUrl: String,
    width: {
      type: String,
      default: '100px'
    },
    height: {
      type: String,
      default: '100px'
    },
    canCut: {
      type: Boolean,
      default: false
    },
    info: {
      type: Boolean,
      default: false
    }, // 裁剪框的大小信息
    outputSize: {
      type: Number,
      default: 0.8
    }, // 裁剪生成图片的质量
    outputType: {
      type: String,
      default: 'jpeg'
    }, // 裁剪生成图片的格式
    canScale: {
      type: Boolean,
      default: true
    }, // 图片是否允许滚轮缩放
    autoCrop: {
      type: Boolean,
      default: true
    }, // 是否默认生成截图框
    // autoCropWidth: 300, // 默认生成截图框宽度
    // autoCropHeight: 200, // 默认生成截图框高度
    fixedBox: {
      type: Boolean,
      default: false
    }, // 固定截图框大小 不允许改变
    fixed: {
      type: Boolean,
      default: true
    }, // 是否开启截图框宽高固定比例
    fixedNumber: {
      type: Array,
      default: () => [1, 1]
    }, // 截图框的宽高比例
    full: {
      type: Boolean,
      default: true
    }, // 是否输出原图比例的截图
    canMove: {
      type: Boolean,
      default: false
    },
    canMoveBox: {
      type: Boolean,
      default: true
    }, // 截图框能否拖动
    original: {
      type: Boolean,
      default: false
    }, // 上传图片按照原始比例渲染
    centerBox: {
      type: Boolean,
      default: true
    }, // 截图框是否被限制在图片里面
    infoTrue: {
      type: Boolean,
      default: true
    } // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
  },
  methods: {
    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJpgOrPng) {
        this.$message.error('请上传JPG或PNG文件!')
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('请上传2MB以下文件!')
      }
      return isJpgOrPng && isLt2M
    },
    customRequest(file) {
      if (this.canCut) {
        this.readFile(file.file)
      } else {
        this.loading = true
        const formData = new FormData()
        formData.append('fileIdcard', file.file)
        uploadImage(formData).then(res => {
          this.loading = false
          this.$emit('uploadSuccess', res.ossUrl)
        })
      }
    },
    readFile(file) {
      var reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = () => {
        this.imageCut.init(reader.result)
      }
    },
    finish() {
      this.$refs.cropper.getCropBlob(data => {
        this.loading = true
        // 上传阿里云服务器
        const formData = new FormData()
        formData.append('fileIdcard', data)
        uploadImage(formData).then(res => {
          this.imageCut.close()
          this.loading = false
          this.$emit('uploadSuccess', res.ossUrl)
        })
      })
    }
  }
}
</script>

css

<style lang="less">
.avatar-uploader > .ant-upload {
  width: 100%;
  height: 100%;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
.cropper-content {
  .cropper {
    width: auto;
    height: 400px;
  }
}
</style>

组件使用及说明

<image-upload
        :imageUrl="form.diagramUrl"
        @uploadSuccess="uploadSuccess"
        width="160px"
        height="90px"
        :can-edit="canCut"
        :fixed-number="[16,9]"
      />

组件调用时需传入canEdit属性,指定组件是否启动图片选取后的裁剪功能,默认值为不启用裁剪;需裁剪时可传入fixedNumber属性,定义裁剪框的宽高比

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Vue.js 相关文章推荐
实用的 vue tags 创建缓存导航的过程实现
Dec 03 Vue.js
vue el-upload上传文件的示例代码
Dec 21 Vue.js
Vue组件简易模拟实现购物车
Dec 21 Vue.js
vue绑定class的三种方法
Dec 24 Vue.js
Vue使用鼠标在Canvas上绘制矩形
Dec 24 Vue.js
vue3使用vue-count-to组件的实现
Dec 25 Vue.js
vue 数据双向绑定的实现方法
Mar 04 Vue.js
vue引入Excel表格插件的方法
Apr 28 Vue.js
一定要知道的 25 个 Vue 技巧
Nov 02 Vue.js
vue @click.native 绑定原生点击事件
Apr 22 Vue.js
vue使用element-ui按需引入
May 20 Vue.js
HTML+VUE分页实现炫酷物联网大屏功能
Vue实现动态查询规则生成组件
详解vue身份认证管理和租户管理
vue点击弹窗自动触发点击事件的解决办法(模拟场景)
vue-element-admin项目导入和导出的实现
May 21 #Vue.js
vue2实现provide inject传递响应式
May 21 #Vue.js
vue使用节流函数的踩坑实例指南
You might like
php 正则 过滤html 的超链接
2009/06/02 PHP
php命名空间学习详解
2014/02/27 PHP
php读取本地json文件的实例
2018/03/07 PHP
关于Curl在Swoole协程中的解决方案详析
2019/09/12 PHP
php获取是星期几的的一些常用姿势
2019/12/15 PHP
Javascript里使用Dom操作Xml
2006/09/20 Javascript
IE不出现Flash激活框的小发现的js实现方法
2007/09/07 Javascript
JS模拟键盘打字效果的方法
2015/08/05 Javascript
nodejs利用http模块实现银行卡所属银行查询和骚扰电话验证示例
2016/12/30 NodeJs
js模拟微博发布消息
2017/02/23 Javascript
本地存储localStorage用法详解
2017/07/31 Javascript
js基于FileSaver.js 浏览器导出Excel文件的示例
2017/08/15 Javascript
深入理解vue-router之keep-alive
2017/08/31 Javascript
基于element-ui组件手动实现单选和上传功能
2018/12/06 Javascript
bootstrap实现嵌套模态框的实例代码
2020/01/10 Javascript
Vue包大小优化的实现(从1.72M到94K)
2021/02/18 Vue.js
Python中的if、else、elif语句用法简明讲解
2016/03/11 Python
详解duck typing鸭子类型程序设计与Python的实现示例
2016/06/03 Python
Python开发中爬虫使用代理proxy抓取网页的方法示例
2017/09/26 Python
Python中偏函数用法示例
2018/06/07 Python
Python+OpenCV图片局部区域像素值处理详解
2019/01/23 Python
python面向对象法实现图书管理系统
2019/04/19 Python
Python自定义一个异常类的方法
2019/06/27 Python
python3 深浅copy对比详解
2019/08/12 Python
使用Tensorflow将自己的数据分割成batch训练实例
2020/01/20 Python
termux中matplotlib无法显示中文问题的解决方法
2021/01/11 Python
使用CSS3的font-face字体嵌入样式的方法讲解
2016/05/13 HTML / CSS
Web Service面试题:如何搭建Axis2的开发环境
2012/06/20 面试题
下面关于"联合"的题目的输出是什么
2013/08/06 面试题
写给女生的道歉信
2014/01/14 职场文书
环境科学专业求职信
2014/08/04 职场文书
岗位职责范本大全
2015/02/26 职场文书
感恩父母主题班会
2015/08/12 职场文书
《金钱的魔力》教学反思
2016/02/20 职场文书
彻底弄懂Python中的回调函数(callback)
2022/06/25 Python
MySQL分布式恢复进阶
2022/07/23 MySQL