DEV Community

Cover image for Crop a picture and upload it to the server with Vue.js
FlyNestor
FlyNestor

Posted on

Crop a picture and upload it to the server with Vue.js

There is a large number of occasions when you have to implement a “select a picture and crop it” feature: for example when a user is uploading a picture of him to customize his profile on a website.

First you need to install vue-cropperjs , a wrapper component for cropperjs.

We will use the method getCroppedCanvas to upload the cropped image to the server. The full documentation about the cropperjs methods is available here.

In the template you can indicate which type of cropper you need. In the example below the cropper has a fixed ratio of 16/9.

<VueCropper 
v-show="selectedFile" ref="cropper" :src="selectedFile" 
:aspectRatio="16/9" :initialAspectRatio="16/9" :autoCropArea="1"
:zoomable="false"
>
</VueCropper>
Enter fullscreen mode Exit fullscreen mode

The replace method is used to rebuild the cropper when you select a file and crop it.

this.$refs.cropper.replace(vm.file);
Enter fullscreen mode Exit fullscreen mode

The getCroppedCanvas method gets a canvas drawn from the cropped image. After you can use HTMLCanvasElement.toBlob to get a blob and upload it to the server with FormData.

Explanation of the terms above:
Blob:
A binary large object (BLOB) is a collection of binary data stored as a single entity. Blobs are typically images, audio or other multimedia objects.

FormData:
To send multipart form data with Axios, you need to use the FormData class.

// Upload cropped image to server if the browser supports `HTMLCanvasElement.toBlob`
this.$refs.cropper.getCroppedCanvas({width: 1280, height: 720}).toBlob((blob) => {

              var data = new FormData();
              data.append('cropped_picture', blob, 'cropped.png')
              ...
              axios.post(load_url,data, {
                      headers: {
                     'Content-Type': 'multipart/form-data'
                     }}
                  ).then(response => {
                  …
                 }).catch(error => {
                 console.log(error)
                 })
      /* second parameter mime_type toBlob set image/png as default */
      } /*, 'image/png' */)
Enter fullscreen mode Exit fullscreen mode

You can see an example on my website Rollideo: video generation from a text. This feature allows the user to choose his own picture to generate a video.

Top comments (0)