DEV Community

WebCraft Notes
WebCraft Notes

Posted on • Updated on • Originally published at webcraft-notes.com

Vue.js: Prepare Images for Upload with Compressor.js

upload and compress image

Introduction:

In this guide, we'll delve into the intricacies of image uploading and compression using Vue 3. Image handling is a fundamental aspect of web development, whether it's avatars, background images, or any visual content. But here's the catch: storage resources are often limited and expensive. That's where the art of image compression comes into play.

Before we upload images to our servers or cloud storage, we have a golden opportunity—image optimization on the client side. By harnessing the capabilities of Vue 3 and the Compressor.js library, we can reduce image file sizes while maintaining visual quality. This not only conserves valuable storage capacity but also significantly enhances website performance and user experience.

In this post, we'll explore the step-by-step process of preparing and compressing images, unlocking a world of efficient storage management and lightning-fast loading times. Join us on this journey to master the art of image optimization with Vue 3 and Compressor.js.

Table of Contents

  1. Setting up the starter files
  2. Compress the image after uploading
  3. Results
  4. Conclusion

Setting up the starter files.
We are going to create a testing project, for example purposes, with typical folders and file structures. We will use Vue js Quick Start tutorials from the official documentation. The final result from the first step will be an empty basic project:

starting project

Next install compressor.js => "npm i compressorjs".

We will add a simple input directly into App.vue that will upload images.

upload image template

Nothing unusual, I will not add any styles for now. So we have starting input and after pressing the button we can choose a file for uploading. That's all functionality.

simple upload input

Compress the image after uploading
In our "test" project we will upload images only on the client side and will not send them into additional storage.

Okay, let's import compressorjs and add an event listener that will call the function "onFileUploaded()" if the input is changed. Then we will update our "onFileUploaded()" function:

  • get files list with the help of "this.$refs";

  • create a new Compressor with a file that could be typed "File" or "Blob" and "options" type Object;

  • add quality option (quality of image that you want to receive);

  • add convertType option (list of accepted image types);

  • success and error methods, that will be called depends on compressed results;

Here is a simple example:

compressing function

Continue reading and check compressing results...

Top comments (0)