Vue2 vue-cropper裁剪图片-使用方法及注意事项

2023-11-17

记录vue-croppe的使用及过程中遇到的问题。

参考文章 Vue2中使用vue-croper插件实现图片上传裁剪--超详细

  • 效果图

  • 安装
npm install vue-cropper 或 yarn add vue-cropper
  • 封装vue-cropper组件,创建pictureCropper.vue组件 
<template>
  <div class="pictureCropper-container">
    <div class="cropper-content-box" :style="{height: cropperHeight, width: cropperWidth}">
      <VueCropper
        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"
      >
      </VueCropper>
    </div>
  </div>
</template>

<script>
import { VueCropper } from 'vue-cropper'
export default {
  name: 'index',
  components:{
    VueCropper,
  },
  props:{
    initialImg:{
      type: String,
      default: ""
    },
    cropperWidth:{
      type: String,
      default: '200px'
    },
    cropperHeight:{
      type: String,
      default: '200px'
    },
    autoCropWidth:{
      type:Number,
      default: 200,
    },
    autoCropHeight:{
      type:Number,
      default: 200,
    },
  },
  watch:{
    initialImg:{
      deep: true,
      immediate: true,
      handler(val){
        this.option.img = val
      }
    }
  },
  data(){
    return {
      previews: {},
      option: {
        img: this.initialImg, // 裁剪图片的地址
        outputSize: 1, // 裁剪生成图片的质量(可选0.1 - 1)
        outputType: 'png', // 裁剪生成图片的格式(jpeg || png || webp)
        info: true, // 图片大小信息
        canScale: true, // 图片是否允许滚轮缩放
        autoCrop: true, // 是否默认生成截图框
        autoCropWidth: this.autoCropWidth, // 默认生成截图框宽度
        autoCropHeight: this.autoCropHeight, // 默认生成截图框高度
        fixed: true, // 是否开启截图框宽高固定比例
        fixedNumber: [1, 1], // 截图框的宽高比例
        full: false, // false按原比例裁切图片,不失真
        fixedBox: true, // 固定截图框大小,不允许改变
        canMove: false, // 上传图片是否可以移动
        canMoveBox: true, // 截图框能否拖动
        original: false, // 上传图片按照原始比例渲染
        centerBox: false, // 截图框是否被限制在图片里面
        height: true, // 是否按照设备的dpr 输出等比例图片
        infoTrue: false, // true为展示真实输出图片宽高,false展示看到的截图框宽高
        maxImgSize: 3000, // 限制图片最大宽度和高度
        enlarge: 1 // 图片根据截图框输出比例倍数
      },
    }
  },
  methods: {
    // 实时预览函数
    realTime (data) {
      this.previews = data
      this.$emit('picturePreview',data)
    },
    // 图片缩放
    changeScale (num) {
      num = num || 1
      this.$refs.cropper.changeScale(num)
    },
    // 向左旋转
    rotateLeft () {
      this.$refs.cropper.rotateLeft()
    },
    // 向右旋转
    rotateRight () {
      this.$refs.cropper.rotateRight()
    },
    // 获取截图base64格式
    getBase64(){
      return new Promise(resolve => {
        this.$refs.cropper.getCropData((data) => {
          resolve(data)
        })
      })
    },
    // 获取截图blob格式
    getBlob(){
      return new Promise(resolve => {
        this.$refs.cropper.getCropBlob((data) => {
          resolve(data)
        })
      })
    }
  }
}
</script>
  • 使用pictureCropper组件
<template>
  <div class="customCropper-container">
    <div class="cropper-title">自定义裁剪</div>
    <div class="cropper-container">
      <div class="operate-picture">
        <PictureCropper
          ref="picture"
          :initialImg="initialImg"
          :cropperHeight="cropperHeight"
          :cropperWidth="cropperWidth"
          :autoCropWidth="autoCropWidth"
          :autoCropHeight="autoCropHeight"
          @picturePreview="picturePreview"
        />
        <div class="operate-button">
          <el-upload
            class="upload-button"
            action="/"
            :before-upload="beforeUploadAction"
            accept="image/*"
          >
            <el-button class="common-button blue-border">上传图片</el-button>
          </el-upload>
          <el-button 
            class="common-button blue-border" 
            @click="rotateLeft"
          >向左旋转</el-button>
          <el-button 
            class="common-button blue-border" 
            @click="rotateRight"
          >向右旋转</el-button>
          <el-button 
            class="common-button blue-border" 
            @click="zoom(1)"
          >放大</el-button>
          <el-button 
            class="common-button blue-border"
            @click="zoom(-1)"
          >缩小</el-button>
          <el-button 
            class="common-button blue-border" 
            @click="download"
          >下载图片</el-button>
        </div>
      </div>
      <div class="preview-picture">
        <div class="picture">
          <div class="preview-container" :style="previews.div">
            <img class="preview-img" :src="previews.url" :style="previews.img">
          </div>
          <div class="preview-container preview-radius" :style="previews.div">
            <img class="preview-img" :src="previews.url" :style="previews.img">
          </div>
        </div>
        <el-button 
            class="common-button blue-border upload-avatar" 
            @click="uploadAvatar('blob')"
        >上传头像</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import PictureCropper from '@/components/pictureCropper/index.vue'
export default {
  name: 'customCropper',
  components:{
    PictureCropper,
  },
  data(){
    return{
      initialImg: require('@/assets/image/fox.jpg'),  // 本地图片用require,链接地址不用
      previews: {},
      cropperHeight: '500px',  // 裁剪图片容器高度
      cropperWidth: '800px',   // 裁剪图片容器宽度
      autoCropWidth: 200,
      autoCropHeight: 200,
    }
  },
  methods:{
    picturePreview(data){
      this.previews = data
    },
    // 向左旋转
    rotateLeft(){
      this.$refs.picture.rotateLeft()
    },
    // 向左旋转
    rotateRight(){
      this.$refs.picture.rotateLeft()
    },
    // 放大、缩小
    zoom(num){
      num = num || 1
      this.$refs.picture.changeScale(num)
    },
    // 下载图片
    async download(){
      let aLink = document.createElement('a')
      aLink.download = '下载裁剪图片'
      let data = await this.$refs.picture.getBase64()
      aLink.href = data
      aLink.click()
    },
    // 上传图片之前
    beforeUploadAction(file){
      return new Promise((resolve, reject) => {
        // 转换为blob
        var reader = new FileReader()
        let reg = /\.jpg$|\.jpeg$|\.gif$|\.png$/i
        // 转化为base64
        reader.readAsDataURL(file)
        let name = file.name
        if (reg.test(name)) {
          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.initialImg = data
            resolve(data)
          }
        } else {
          this.$message.error('请上传图片')
          reject()
        }
      })
    },
    // 上传头像到服务器
    async uploadAvatar(type){
      if(type === 'blob'){
        // 获取截图的blob数据
        let data = await this.$refs.picture.getBlob()
        this.uploadPhoto(data)
      }
    },
    async uploadPhoto(blob){
      try{
        const formData = new FormData()
        formData.append('file',blob,'.jpg')
        // 上传头像的业务代码...省略
        this.$message.success('修改头像成功')
      } catch (error){
        this.$message.error('修改头像失败')
      }
    }
  }
}
</script>

  • 问题1  图片转换报错

问题描述:在使用组件时,报错 Uncaught (in promise) TypeError: First argument to DataView constructor must be an ArrayBuffer at new DataView (<anonymous>)

原因:因为在本地使用了mock.js,导致图片转换报错

解决方法: 关闭本地mock服务,在main.js 注释mock.js的引入(该解决方案参考博客https://www.cnblogs.com/mary-123/p/12029514.html)在网上找了很久关于这个报错的解决方法,终于找到了这个方法,太不容易了

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Vue2 vue-cropper裁剪图片-使用方法及注意事项 的相关文章

随机推荐

  • springboot整合JSR303校验

    4 7 JSR303校验 4 7 1 统一校验的需求 前端请求后端接口传输参数 是在controller中校验还是在Service中校验 答案是都需要校验 只是分工不同 Contoller中校验请求参数的合法性 包括 必填项校验 数据格式校
  • coalesce 函数详解与学习记录

    1 在工作中都用到了此函数 特此学习并记录一下 2 coalesce 用途 1 将空值替换成其他值 2 返回第一个非空值 3 SQL实例 一 select coalesce success cnt 1 from tableA 当succes
  • Python使用管道、队列、zeromq进行IPC速度对比测试

    管道 import sys from multiprocessing import Process Pipe import time import result msg list for i in range 100 msg list ap
  • YOLOv5 backbone(一)

    Backbone概览及参数 Parameters nc 80 number of classes depth multiple 0 33 model depth multiple width multiple 0 50 layer chan
  • 利用外部中断和时间中断计数0-999显示在数码管上(考题)

    include
  • Ubuntu(20.04):设置DNS

    编辑文件 etc systemd resolved conf 设置DNS 8 8 8 8 114 114 114 114 保存退出后 以sudo身份运行 systemctl restart systemd resolved systemct
  • 开源之父--Linus

    Git 很多人都知道 Linus在1991年创建了开源的Linux 从此 Linux系统不断发展 已经成为最大的服务器系统软件了 Linus虽然创建了Linux 但Linux的壮大是靠全世界热心的志愿者参与的 这么多人在世界各地为Linux
  • Python3 初学 DAY2

    num1 minute py minute 7 24 60 print minute num2 print py 注 显示颜色格式 033 显示方式 字体色 背景色m 033 0m 显示颜色参数 显示方式 效果 字体色 背景色 颜色描述 0
  • spark报Got an error when resolving hostNames. Falling back to /default-rack for all

    一 报错代码如下 21 06 01 20 13 36 INFO yarn SparkRackResolver Got an error when resolving hostNames Falling back to default rac
  • 【Spring】Spring官方文档笔记

    Spring 官方文档 和任何一本spring书籍相比 它都更新更全 文章目录 Spring 1 控制反转 Inversion of Control IoC 1 1 依赖注入 dependency injection DI 1 Spring
  • java虚拟机+分隔符

    java 入门 java 虚拟机 1 java虚拟机的平台可移植性 只要将java虚拟机安装于不同平台 我们编译的 class 文件就可以运行 2 jdk java开发 3 jre java运行时环境 jdk jre 下载安装后必须在环境变
  • C语言:利用队列逆置栈

    关注作者 Aqu 蓝空 定义一些功能的函数 void InitStack SqStack S 栈的初始化 void Push SqStack S int data 入栈 int Pop SqStack S 出栈 void StackTrav
  • 根据身份证号获取出生日期,年龄,性别

    java语言 根据身份证号获取出生日期 年龄 性别 测试程序 public class TestUtils public static void main String args String idcard xxxxxxxxxxxxxxxx
  • oracle 获取日期的毫秒_Oracle 毫秒时间戳

    其实很早以前就经常碰到这个问题 就是得到自1970年1月1日以来的秒数 这个问题很容易解决 SQL gt SELECT SYSDATE TO DATE 1970 1 1 8 YYYY MM DD HH24 86400 FROM DUAL S
  • Linux学习笔记-----缓冲区概念及git使用

    一 编译文件 编译器是如何知道我的生成软件需要被重新编译了 根据文件的修改时间来的 因为用户不可能同时修改多个问题 所以文件修改总是有先后顺序的 又因为 源文件和可执行程序时间总是交叉 二 缓冲区概念及理解 1 概念 就是一块内存 刷新策略
  • clickhouse导入数据 DBeaver大坑

    测试数据有一亿条需要导入数据库 使用DBeaver自带导入数据功能 结果放置一晚才导入一千万条 估计导入设置有问题 于是寻找合适方式 记录如下 首先将待导入的csv数据表45G 传输到clickhouse所在的服务器 在数据库中提前建好表
  • 魔方机器人之硬件篇

    待续 点击打开链接 思睿硬件设计博客
  • 面向组织分析的内容

    声明 本文是学习GB T 42859 2023 航天产品质量问题三个面向分析方法实施要求 而整理的学习笔记 分享出来希望更多人受益 如果存在侵权请及时联系我们 1 范围 本文件规定了航天产品质量问题三个面向分析方法实施的一般要求 程序和分析
  • 进制转换(C++)

    文章目录 一 任意2 36进制数转换为10进制数 1 1 c 代码实现 二 十进制转换为其他进制 2 1 方法一 2 2 c 代码实现 2 3 方法二 2 4 Demo 一 任意2 36进制数转换为10进制数 以二进制转换为十进制为例 基本
  • Vue2 vue-cropper裁剪图片-使用方法及注意事项

    记录vue croppe的使用及过程中遇到的问题 参考文章 Vue2中使用vue croper插件实现图片上传裁剪 超详细 效果图 安装 npm install vue cropper 或 yarn add vue cropper 封装vu