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

Vue3 realizes the image magnifying glass effect

This article example shares the specific code of ...

Full analysis of web page elements

Relative Length Units em Description: Relative len...

Various correct postures for using environment variables in Webpack

Table of contents Write in front Business code us...

How to set remote access permissions in MySQL 8.0

The previous article explained how to reset the M...

Implementing a simple whack-a-mole game in JavaScript

This article shares the specific code for JavaScr...

mysql5.6.8 source code installation process

Kernel: [root@opop ~]# cat /etc/centos-release Ce...

MySQL 8.0.15 installation and configuration tutorial under Win10

What I have been learning recently involves knowl...

Analysis of the operating principle and implementation process of Docker Hub

Similar to the code hosting service provided by G...

Detailed explanation of basic interaction of javascript

Table of contents 1. How to obtain elements Get i...

Detailed explanation of the marquee attribute in HTML

This tag is not part of HTML3.2 and is only suppo...

How to expand the disk partition for centos system

Problem/failure/scenario/requirement The hard dis...

A brief discussion on the synchronization solution between MySQL and redis cache

Table of contents 1. Solution 1 (UDF) Demo Case 2...

Six inheritance methods in JS and their advantages and disadvantages

Table of contents Preface Prototype chain inherit...

Using JS to implement a simple calculator

Use JS to complete a simple calculator for your r...