专业编程教程与实战项目分享平台

网站首页 > 技术文章 正文

vue-img-cutter图片裁剪,示例

ins518 2024-11-23 16:44:06 技术文章 10 ℃ 0 评论

简介:

vue-img-cutter,是简单易用的vue图片裁剪插件,支持旋转、缩放、平移、固定尺寸、固定比例、远程图片裁剪等等。只需要很少的代码就可以完成,当然也是可以更加调整具体的参数,去适合自己的业务需求。



软件截图效果:



使用方法:

  1. 安装 npm install vue-img-cutter --save-dev 或者 yarn add vue-img-cutter;
  2. 将ImgCutter引入到项目中,自定义一个index.vue文件,编写代码如下
<template>
  <div class="img_cutter_main">
    <!-- 文档 https://gitee.com/GLUESTICK/vue-img-cutter -->
    <ImgCutter
      :cross-origin="true"
      :tool-bgc="none"
      :is-modal="true"
      :show-choose-btn="true"
      :lock-scroll="true"
      :box-width="600"
      :box-height="400"
      :cut-width="200"
      :cut-height="200"
      :size-change="true"
      :move-able="true"
      @cutDown="xztpCutDown"
    >
      <button slot="open">选择图片</button>
    </ImgCutter>
  </div>
</template>

<script>
import ImgCutter from 'vue-img-cutter'
export default {
  name: "ImgCutterMain",
  components: {
    ImgCutter
  },
  methods: {
    xztpCutDown(fileName) {
      // let that = this

      console.log(fileName, fileName.dataURL, '确定裁剪后的base64')

      var imgGs = fileName.dataURL.split(';')[0].split('/')[1]
      var file = this.dataURLtoBlob(fileName.dataURL, '裁剪图片.' + imgGs)

      console.log(file, 'file')//裁剪后file文件
      var formData = new FormData()
      formData.append('file', file)

      // 上传接口调用
      // ----------
    },
    //将base64转换为file
    dataURLtoBlob: function(dataurl, name) {
      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], name, { type: mime })
    }
  }
}
</script>

<style scoped>

</style>

以上代码只是用到了部分的参数,详细参数说明,可以访问https://gitee.com/GLUESTICK/vue-img-cutter,去查看~~

这里只是为了展示出基本的功能,上面也有写了两个方法:

1、xztpCutDown(),是获取裁剪后的文件内容,包括base64 和 转换为file文件的方法,以及可以在方法内去调用上传文件的方法。

2、dataUrlToBlob(),顾名思义,这里是为了转换file文件Blob格式

编译,选择文件后界面的效果如下:


裁剪后,打印出的数据见下图:

也可以把fileName全打印出来,如下:

插槽的使用:

以上只是用的slot=“open”,其他的大家可以一一去试,这里就不做详细地说明了,(任务来了~~得搬砖去了,嘿嘿)

写到这里,就告一段落了,可以自己yarn add ... 去试一下,感觉还挺有那么回事的。。搬砖了~~~~

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表