Do you know how to use vue-cropper to crop pictures in vue?

Do you know how to use vue-cropper to crop pictures in vue?

Official website:

https://github.com/xyxiao001/vue-cropper

1. Installation:

npm install vue-cropper 

or

yarn add vue-cropper

2. Use:

import VueCropper from 'vue-cropper'

Set up component :

export default {
  components:
    VueCropper
  }
}

Insert in template : (a div is needed outside to set the size of the plug-in display)

<vueCropper
      ref="cropper"
      :img="option.img"
      :outputSize="option.size"
      :outputType="option.outputType"
></vueCropper>
    data(){
      return {
         option:{
            img: 'imgUrl', // URL or base64 of img
            size: 1,
            outputType: 'png',
         }
      }
    }

3. Built-in methods:

name Function default value Optional Values
img The address of the cropped image null url address / base64 / blob
outputSize The quality of the cropped image 1 0.1 - 1
outputType The address of the cropped image jpg (jpg needs to be passed in jpeg) jpeg / png / web

Built-in method : call the plugin via this.$refs.cropper .

this.$refs.cropper.startCrop() starts taking screenshots (if the screenshot frame is not set, start the screenshot frame through this)

this.$refs.cropper.stopCrop() stops taking screenshots

this.$refs.cropper.clearCrop() Clear screenshot

this.$refs.cropper.getCropData() Get the screenshot information (get the screenshot URL or base64)

    // Get the base64 data of the screenshot this.$refs.cropper.getCropData((data) => {
      // do something
      console.log(data)
    })
    // Get the screenshot blob data this.$refs.cropper.getCropBlob((data) => {
      // do something
      console.log(data)
    })

4. Use:

<template>
  <div>
    <el-dialog title="Picture cropping" :visible.sync="show" append-to-body width="950px" center>
      <div class="cropper-content">
        <div class="cropper-box">
          <div class="cropper">
            <vue-cropper 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" @imgLoad="imgLoad">
            </vue-cropper>
          </div>
          <!--Bottom operation tool button-->
          <div class="footer-btn">
            <div class="scope-btn">
              <label class="btn" for="uploads">Select an image</label>
              <input type="file" id="uploads" style="position:absolute; clip:rect(0 0 0 0);" accept="image/png, image/jpeg, image/gif, image/jpg" @change="selectImg($event)">
              <el-button size="mini" type="danger" plain icon="el-icon-zoom-in" @click="changeScale(1)">Zoom in</el-button>
              <el-button size="mini" type="danger" plain icon="el-icon-zoom-out" @click="changeScale(-1)">Zoom out</el-button>
              <el-button size="mini" type="danger" plain @click="rotateLeft">↺ Rotate left</el-button>
              <el-button size="mini" type="danger" plain @click="rotateRight">↻ Rotate right</el-button>
            </div>
            <div class="upload-btn">
              <el-button size="mini" type="success" @click="uploadImg('blob')">Upload image<i class="el-icon-upload"></i></el-button>
            </div>
          </div>
        </div>
        <!--Preview effect picture-->
        <div class="show-preview">
          <div :style="previews.div" class="preview">
            <img :src="previews.url" :style="previews.img">
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { VueCropper } from 'vue-cropper'
export default {
  name: "CropperImage",
  components:
    VueCropper
  },
  data () {
    return {
      show: this.visible,
      name: this.Name,
      previews: {},
      option: {
        img: '', //Address of cropped image outputSize: 1, //Quality of cropped image (optional 0.1 - 1)
        outputType: 'jpeg', //crop to generate the image format (jpeg || png || webp)
        : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : :
    };
  },
  props: {
    visible:
      type: Boolean,
      default: false
    },
    Name:
      type: String,
      default: ''
    }
  },
  watch:
    visible () {
      this.show = this.visible
    }
  },
  methods: {
    // Initialization function imgLoad (msg) {
    },
    //Image scaling changeScale (num) {
      num = num || 1
      this.$refs.cropper.changeScale(num)
    },
    //Rotate left rotateLeft () {
      this.$refs.cropper.rotateLeft()
    },
    //Rotate right rotateRight () {
      this.$refs.cropper.rotateRight()
    },
    //Real-time preview function realTime (data) {
      this.previews = data
    },
    //Select an image selectImg (e) {
      let file = e.target.files[0]
      if (!/\.(jpg|jpeg|png|JPG|PNG)$/.test(e.target.value)) {
        this.$message({
          message: 'Image type requirements: jpeg, jpg, png',
          type: "error"
        });
        return false
      }
      //Convert to blob
      let reader = new FileReader()
      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.option.img = data
      }
      //Convert to base64
      reader.readAsDataURL(file)
    },
    //Upload image uploadImg (type) {
      let _this = this
      if (type === 'blob') {
        // Get the screenshot blob data this.$refs.cropper.getCropBlob(async (data) => {
          let formData = new FormData();
          formData.append('file', data, new Date().getTime() + '.png')
          // Call axios to upload let { data: res } = await _this.$http.post(`${msBaseUrl}common-tools-web/file/upload/image`, formData)
          if (res.code === 200) {
            _this.$message({
              message: res.desc,
              type: "success"
            });
            let data = res.result
            let imgInfo = {
              name: data.name,
              id: data.id,
              url: data.url
            };
            _this.$emit('uploadImgSuccess', imgInfo);
          } else {
            _this.$message({
              message: 'File service abnormality, please contact the administrator! ',
              type: "error"
            })
          }
        })
      }
    }
  }
}
</script>
<style scoped lang="less">
.cropper-content {
  display: flex;
  display: -webkit-flex;
  justify-content: flex-end;
  .cropper-box {
    flex: 1;
    width: 100%;
    .cropper {
      width: auto;
      height: 300px;
    }
  }
  .show-preview {
    flex: 1;
    -webkit-flex: 1;
    display: flex;
    display: -webkit-flex;
    justify-content: center;
    .preview {
      overflow: hidden;
      border: 1px solid #67c23a;
      background: #cccccc;
    }
  }
}
.footer-btn {
  margin-top: 30px;
  display: flex;
  display: -webkit-flex;
  justify-content: flex-end;
  .scope-btn {
    display: flex;
    display: -webkit-flex;
    justify-content: space-between;
    padding-right: 10px;
  }
  .upload-btn {
    flex: 1;
    -webkit-flex: 1;
    display: flex;
    display: -webkit-flex;
    justify-content: center;
  }
  .btn {
    outline: none;
    display: inline-block;
    line-height: 1;
    white-space: nowrap;
    cursor: pointer;
    -webkit-appearance: none;
    text-align: center;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    outline: 0;
    -webkit-transition: 0.1s;
    transition: 0.1s;
    font-weight: 500;
    padding: 8px 15px;
    font-size: 12px;
    border-radius: 3px;
    color: #fff;
    background-color: #409eff;
    border-color: #409eff;
    margin-right: 10px;
  }
}
</style>

Effect:

insert image description here

Summarize

This article ends here. I hope it can be helpful to you. I also hope you can pay more attention to more content on 123WORDPRESS.COM!

You may also be interested in:
  • Springboot+Vue-Cropper realizes the effect of avatar cutting and uploading
  • vue-cropper component realizes image cutting and uploading
  • vue-cropper plug-in realizes the encapsulation of image capture and upload component
  • Detailed explanation of how to use vue-cropper, a Vue image cropping plugin
  • Vue-cropper The basic principles and ideas of picture cropping
  • Encapsulating Vue based on cropper.js to realize online image cropping component function

<<:  Detailed explanation of the solution to keep the content within the container in flex layout

>>:  Form submission page refresh does not jump

Recommend

Detailed explanation of MySQL 8's new feature ROLE

What problems does MySQL ROLE solve? If you are a...

Detailed explanation of MySQL data grouping

Create Group Grouping is established in the GROUP...

What you need to know about creating MySQL indexes

Table of contents Preface: 1. Create index method...

Detailed examples of Docker-compose networks

Today I experimented with the network settings un...

The webpage cannot be opened because the div element lacks a closing tag

At first I thought it was a speed issue, so I late...

How to implement responsiveness in Vue source code learning

Table of contents Preface 1. Key Elements of a Re...

Implementation example of uploading multiple attachments in Vue

Table of contents Preface Core code File shows pa...

Mysql master-slave synchronization configuration scheme under Centos7 system

Preface Recently, when working on a high-availabi...

Solution to the problem that VC6.0 cannot be used when installed on WIN10

VC6.0 is indeed too old VC6.0 is a development to...

A practical record of an accident caused by MySQL startup

Table of contents background How to determine whe...

How to use MyCat to implement MySQL master-slave read-write separation in Linux

Table of contents Linux-Use MyCat to implement My...

JavaScript implements an input box component

This article example shares the specific code for...

Instructions for recovering data after accidental deletion of MySQL database

In daily operation and maintenance work, backup o...

How to check PCIe version and speed in Linux

PCIE has four different specifications. Let’s tak...

Using puppeteer to implement webpage screenshot function on linux (centos)

You may encounter the following problems when ins...