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

How to build php7 with docker custom image

First, perform a simple Docker installation. To c...

CSS3 to achieve simple white cloud floating background effect

This is a very simple pure CSS3 white cloud float...

Detailed explanation of Nginx access restriction configuration

What is Nginx access restriction configuration Ng...

Docker nginx implements one host to deploy multiple sites

The virtual machine I rented from a certain site ...

SSM implements the mysql database account password ciphertext login function

introduction Our company is engaged in the resear...

Vue uses rules to implement form field validation

There are many ways to write and validate form fi...

How to set remote access permissions in MySQL 8.0

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

Bootstrap 3.0 study notes buttons and drop-down menus

The previous article was a simple review of the B...

Detailed explanation of how to mount remote file systems via SSH on Linux

Features of SSHFS: Based on FUSE (the best usersp...

HTML table markup tutorial (22): row border color attribute BORDERCOLORLIGHT

Within rows, light border colors can be defined i...

JavaScript implements displaying a drop-down box when the mouse passes over it

This article shares the specific code of JavaScri...

Example of how to import nginx logs into elasticsearch

The nginx logs are collected by filebeat and pass...

Detailed tutorial on deploying Jenkins based on docker

0. When I made this document, it was around Decem...