vue-cropper实现裁剪图片

本文实例为大家分享了vue-cropper实现裁剪图片的具体代码,供大家参考,具体内容如下

先展示一下效果

如何使用:

1、安装 

npm install vue-cropper  //(如果安装不上,用cnpm)

2、直接贴代码爽快人就是这样

<template>
  <el-dialog
    title="裁剪图片"
    :visible.sync="visible"
    @close="onCallback(false)"
    class="handleDialog"
    width="1000px"
  >
    <div class="wrap">
      <div class="main">
        <div class="cropperContent">
          <div class="cropper">
            <vueCropper
              ref="cropper"
              :img="option.img"
              :outputSize="option.size"
              :outputType="option.outputType"
              :info="true"
              :full="option.full"
              :canMove="option.canMove"
              :canMoveBox="option.canMoveBox"
              :original="option.original"
              :autoCrop="option.autoCrop"
              :autoCropWidth="option.autoCropWidth"
              :autoCropHeight="option.autoCropHeight"
              :fixedBox="option.fixedBox"
              @realTime="realTime"
              @imgLoad="imgLoad"
            ></vueCropper>
          </div>
          <div class="previewBox">
            <div class="title">实时预览</div>
            <div
              class="showPreview"
              :style="{
                width: previews.w + 'px',
                height: previews.h + 'px',
              }"
            >
              <div :style="previews.div" class="preview">
                <img :src="previews.url" :style="previews.img" />
              </div>
            </div>
          </div>
        </div>
 
        <div class="footerButton">
          <div class="scopeButton">
            <label class="localButton" for="uploads">本地图片</label>
            <input
              type="file"
              id="uploads"
              class="inputFile"
              accept="image/png, image/jpeg, image/gif, image/jpg"
              @change="uploadImg($event)"
            />
 
            <el-button
              type="primary"
              @click="changeScale(1)"
              icon="el-icon-plus"
            ></el-button>
            <el-button
              type="primary"
              @click="changeScale(-1)"
              icon="el-icon-minus"
            ></el-button>
            <el-button
              type="primary"
              @click="rotateLeft"
              icon="el-icon-refresh-left"
            ></el-button>
            <el-button
              type="primary"
              @click="rotateRight"
              icon="el-icon-refresh-right"
            ></el-button>
          </div>
          <div class="uploadButton">
            <el-button
              @click="down('blob')"
              type="primary"
              icon="el-icon-download"
              >下载</el-button
            >
            <el-button
              @click="uploadNewPic"
              type="primary"
              icon="el-icon-upload2"
              >上传</el-button
            >
          </div>
        </div>
      </div>
      <div class="end">
        <el-button type="primary" @click="saveNewPic">保存</el-button>
        <el-button @click="onCallback(false)">取消</el-button>
      </div>
    </div>
  </el-dialog>
</template>
<script>
import { VueCropper } from "vue-cropper";
import { imgView, imgUploadUrl, uploadImg } from "services";
import { alerts } from "js/yydjs.js";
export default {
  components: { VueCropper },
  data() {
    return {
      imgView,
      picId: "",
      newPicId: "",
      crap: false,
      previews: {},
      option: {
        img: "",
        size: 1,
        full: false, //输出原图比例截图 props名full
        outputType: "png",
        canMove: true,
        original: false,
        canMoveBox: false,
        autoCrop: true,
        autoCropWidth: 300,
        autoCropHeight: 300,
        fixedBox: true,
      },
      downImg: "#",
      cate: "",
      ratio: 1,
    };
  },
  mounted() {
    this.option.img = this.imgView + this.picId;
    this.option.autoCropHeight = this.option.autoCropWidth * this.ratio;
  },
  methods: {
    saveNewPic() {
      if (!this.newPicId) {
        return alerts("请上传裁剪后的图片");
      }
      this.onCallback(this.newPicId);
    },
    changeScale(num) {
      num = num || 1;
      this.$refs.cropper.changeScale(num);
    },
    rotateLeft() {
      this.$refs.cropper.rotateLeft();
    },
    rotateRight() {
      this.$refs.cropper.rotateRight();
    },
    // 实时预览函数
    realTime(data) {
      console.log(data, "realTime");
      this.previews = data;
    },
    // 将base64转换为文件 百度随便找的 看需求使用
    dataURLtoFile(dataurl, filename) {
      var arr = dataurl.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, { type: mime });
    },
    uploadNewPic() {
      this.$refs.cropper.getCropData((data) => {
        let name = new Date().getTime();
        let file = this.dataURLtoFile(data, `${name}.png`);
        console.log(file, "ssss");
        let fd = new FormData();
        fd.append("file", file);
        fd.append("cate", this.cate);
        uploadImg(fd).then((res) => {
          if (res) {
            let { scaleRelativePath = "" } = res.body;
            this.newPicId = scaleRelativePath;
            alerts("上传成功", "success"); // 自己写的弹框
          }
        });
      });
    },
    down(type) {
      // event.preventDefault()
      var aLink = document.createElement("a");
      aLink.download = "author-img";
      // 输出
      if (type === "blob") {
        this.$refs.cropper.getCropBlob((data) => {
          console.log(data, type);
          this.downImg = window.URL.createObjectURL(data);
          // aLink.download = this.downImg;
          console.log(this.downImg);
          aLink.href = window.URL.createObjectURL(data);
          aLink.click();
        });
      } else {
        this.$refs.cropper.getCropData((data) => {
          this.downImg = data;
          aLink.href = data;
          aLink.click();
        });
      }
    },
    uploadImg(e) {
      //上传图片
      // this.option.img
      var file = e.target.files[0];
      if (!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG)$/.test(e.target.value)) {
        alerts("图片类型必须是.gif,jpeg,jpg,png,bmp中的一种");
        return false;
      }
      var reader = new FileReader();
      reader.onload = (e) => {
        let data;
        if (typeof e.target.result === "object") {
          // 把Array Buffer转化为blob 如果是base64不需要
          data = window.URL.createObjectURL(new Blob([e.target.result]));
        } else {
          data = e.target.result;
        }
        this.option.img = data;
      };
      // 转化为base64
      // reader.readAsDataURL(file)
      // 转化为blob
      reader.readAsArrayBuffer(file);
    },
    imgLoad(msg) {
      console.log(msg, "msg");
    },
  },
};
</script>
<style lang="scss" scoped>
@import "~css/public.scss";
.handleDialog {
  @include cententCenterDialog;
  .cropperContent {
    display: flex;
    justify-content: space-between;
    padding-left: 20px;
    .cropper {
      width: 400px;
      height: 400px;
      border: 1px solid #ddd;
    }
    .previewBox {
      flex: 1;
      display: flex;
      justify-content: center;
      flex-direction: column;
      align-items: center;
      .title {
        font-size: 18px;
        height: 36px;
        margin-bottom: 20px;
      }
      .showPreview {
        flex: 1;
        display: flex;
        justify-content: center;
        .preview {
          overflow: hidden;
          background: #eeeeee;
          border: 1px solid #eeeeee;
        }
      }
    }
  }
  .footerButton {
    margin-top: 30px;
    margin-left: 20px;
    display: flex;
    justify-content: flex-end;
    .scopeButton {
      width: 400px;
      display: flex;
      justify-content: space-between;
    }
    .uploadButton {
      flex: 1;
      display: flex;
      justify-content: center;
    }
    .localButton {
      cursor: pointer;
      color: #ffffff;
      background: #409eff;
      padding: 10px 15px;
      border-radius: 3px;
      appearance: none;
      display: flex;
      align-self: center;
      margin-right: 10px;
    }
    .inputFile {
      width: 180px;
      position: absolute;
      clip: rect(0 0 0 0);
    }
  }
}
</style>

3、说明,支持网络图片也支持本地图片,图片如果需要上传,我是通过base64转文件,再上传的。

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

(0)

相关推荐

  • vue-image-crop基于Vue的移动端图片裁剪组件示例

    本文介绍了vue-image-crop基于Vue的移动端图片裁剪组件示例,分享给大家,具体如下: 代码地址:https://github.com/jczzq/vue-image-crop vue-image-crop 基于Vue的移动端图片裁剪组件 组件使用URL.createObjectURL()等新特性,使用前注意兼容问题.IE >= 10 注意:该组件适用于 PC 端,不推荐手机端使用. 功能预览 快速开始 安装Node >= 8.9.0(推荐LTS = 8.11.0) # 安装 vue

  • vue实现移动端图片裁剪上传功能

    本文实例为大家分享了vue移动端图片裁剪上传的具体代码,供大家参考,具体内容如下 1. 安装cropperjs依赖库 npm install cropperjs 2. 编写组件SimpleCropper.vue <template> <div class="v-simple-cropper"> <slot> <button @click="upload">上传图片</button> </slot>

  • 基于Vue的移动端图片裁剪组件功能

    最近项目上要做一个车牌识别的功能.本来以为很简单,只需要将图片扔给后台就可以了,但是经测试后识别率只有20-40%.因此产品建议拍摄图片后,可以对图片进行拖拽和缩放,然后裁剪车牌部分上传给后台来提高识别率.刚开始的话还是百度了一下看看有没有现成的组件,但是找来找去都没有找到一个合适的,还好这个功能不是很着急,因此自己周末就在家里研究一下. Demo地址:https://vivialex.github.io/demo/imageClipper/index.html 下载地址:https://git

  • Vue-cropper 图片裁剪的基本原理及思路讲解

    一:裁剪的思路: 1-1,裁剪区域:需要进行裁剪首先需要形成裁剪区域,裁剪区域的大小和我们的鼠标移动的距离相关联,鼠标移动有多远,裁剪区域就有多大.如下图: 1-2 裁剪区域的宽和高的计算: 如上图,鼠标的横向移动距离和纵向移动距离就形成了裁剪区域的宽和高.那么裁剪区域的宽和高的计算是:当我们点下鼠标时,就能够通过event事件 对象获取鼠标点击位置,e.clientX 和 e.clientY; 当鼠标进行移动的时候,也能通过event获取鼠标的位置,通过两次鼠标位置的改变,就能够获得 鼠标移动

  • vue移动端裁剪图片结合插件Cropper的使用实例代码

    之前写了一个上传头像的功能模块,以下的内容是描述上传头像过程中裁剪图片插件结合vue的一个使用. 当然,使用就安装 npm install cropperjs 接着再引入 import Cropper from 'cropperjs' 下面是源码 <template> <div id="demo"> <!-- 遮罩层 --> <div class="container" v-show="panel">

  • vue.js 实现图片本地预览 裁剪 压缩 上传功能

    以下代码涉及 Vue 2.0 及 ES6 语法. 目标 纯 javascrpit 实现,兼容ie9及以上浏览器,在本地做好文件格式.长宽.大小的检测,减少浏览器交互. 现实是残酷的,为了兼容Ie9 还是用上了 flash,第二篇来解释解释. 代码结构 <div id="wrap"> <label> 点我上传图片 <input type='file' @change="change" ref="input"> &

  • 详解vue项目中实现图片裁剪功能

    演示地址 https://my729.github.io/picture-crop-demo/dist/#/ 前言 vue版本:3.6.3 https://cli.vuejs.org/zh/ cropperjs: 1.5.1 https://github.com/fengyuanchen/cropperjs elementUI https://element.eleme.io/#/zh-CN 使用 cropperjs插件 和 原生canvas 两种方式实现图片裁剪功能 使用cropperjs插件

  • vue+element实现图片上传及裁剪功能

    本文实例为大家分享了vue+element实现图片上传及裁剪的具体代码,供大家参考,具体内容如下 随便写的一个小demo 功能是没有任何问题 可能里面会有一些小细节没有优化 1 .安装 vue-cropper npm install vue-cropper 2.组件内使用 import { VueCropper } from 'vue-cropper' components: { VueCropper, }, 具体可见官网 demo <template> <div> <h1&

  • cropper js基于vue的图片裁剪上传功能的实现代码

    前些日子做了一个项目关于vue项目需要头像裁剪上传功能,看了一篇文章,在此基础上做的修改完成了这个功能,与大家分享一下.原文:http://www.jb51.net/article/135719.htm 首先下载引入cropper js, npm install cropper js --save 在需要的页面引入:import Cropper from "cropper js" html的代码如下: <template> <div id="demo&quo

  • vue-cli结合Element-ui基于cropper.js封装vue实现图片裁剪组件功能

    前端工作中,经常需要图片裁剪的场景,cropper.js是一款优秀的前端插件,api十分丰富. 本文是在vue-cli项目下封装图片裁剪插件,效果图如下: 话不多说,看步骤吧. 第一步:准备开发环境 cropper.js是基于jquery的,所以要先安装jquery 执行命令: npm  install --save-dev jquery cropper 为webpack配置添加jquery的映射 修改webpack.base.conf.js配置,添加标红的一行 第二步:新建图片裁剪组件 ind

随机推荐