Vue uses canvas to realize image compression upload

Vue uses canvas to realize image compression upload

This article shares the specific code of Vue using canvas to achieve image compression upload for your reference. The specific content is as follows

Scenario: such as user avatar, etc.

For uploading large-size images, compression on the front end not only saves traffic, but also greatly improves the user experience.

Two aspects:

1. Since the uploaded image size is relatively small, the upload speed will be faster and the interaction will be smoother. At the same time, the risk of upload failure caused by network abnormalities is greatly reduced.
2. The image upload function of many websites will limit the size of images, especially avatar uploads. It is very common to limit it to 5M or 2M (but I took an avatar with a SLR, so it is normal for the photo to exceed 2M, and the image needs to be processed before it can be uploaded). If compression can be performed on the front end, then theoretically there is no need to limit the image size.

Example:

Main technology: Use the drawImage() method of canvas . (Appendix: canvas.toDataURL() or canvas.toBlob())

ctx.drawImage(image, dx, dy);
ctx.drawImage(image, dx, dy, dWidth, dHeight);
ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);

Example:

//html
<input id="file" type="file">

// JS
var eleFile = document.querySelector('#file');

//Some elements and objects needed to compress images var reader = new FileReader(), img = new Image();

//Selected file object var file = null;

//Scaling the canvas required for the image
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');

// After the base64 address image is loaded, img.onload = function () {
    //Original size of the image var originWidth = this.width;
    var originHeight = this.height;
    // Maximum size limit var maxWidth = 400, maxHeight = 400;
    // Target size var targetWidth = originWidth, targetHeight = originHeight;
    // The image size exceeds the limit of 400x400 if (originWidth > maxWidth || originHeight > maxHeight) {
        if (originWidth / originHeight > maxWidth / maxHeight) {
            // Wider, limit the size according to the width targetWidth = maxWidth;
            targetHeight = Math.round(maxWidth * (originHeight / originWidth));
        } else {
            targetHeight = maxHeight;
            targetWidth = Math.round(maxHeight * (originWidth / originHeight));
        }
    }
        
    // canvas scales the image canvas.width = targetWidth;
    canvas.height = targetHeight;
    // Clear the canvas context.clearRect(0, 0, targetWidth, targetHeight);
    // Image compression context.drawImage(img, 0, 0, targetWidth, targetHeight);
    // Convert canvas to blob and upload canvas.toBlob(function (blob) {
        // Ajax upload of pictures var xhr = new XMLHttpRequest();
        // File upload successful xhr.onreadystatechange = function() {
            if (xhr.status == 200) {
                // xhr.responseText is the returned data}
        };
        // Start uploading xhr.open("POST", 'upload.php', true);
        xhr.send(blob);    
    }, file.type || 'image/png');
};

// Convert the file to base64 to get the original size of the image reader.onload = function(e) {
    img.src = e.target.result;
};
eleFile.addEventListener('change', function (event) {
    file = event.target.files[0];
    // The selected file is an image if (file.type.indexOf("image") == 0) {
        reader.readAsDataURL(file);    
    }
});

Notice:

The image will be distorted on the mobile side. You need to enlarge the canvas according to the device's DPR and then use CSS to force it to recover.

// Get device dpr
getPixelRatio: function(context) {
    let backingStore = context.backingStorePixelRatio ||
    context.webkitBackingStorePixelRatio ||
    context.mozBackingStorePixelRatio ||
    context.msBackingStorePixelRatio ||
    context.oBackingStorePixelRatio ||
    context.backingStorePixelRatio || 1;
    return (window.devicePixelRatio || 1) / backingStore;
}

// something like this const ctx = this.canvas.getContext("2d");
const dpr = this.getPixelRatio(ctx);
this.$refs.postImg.crossOrigin = "Anonymous";
var oldWidth = this.canvas.width;
var oldHeight = this.canvas.height;
this.canvas.style.width = oldWidth + 'px'; 
this.canvas.style.height = oldHeight + 'px';
this.canvas.width = oldWidth * dpr;
this.canvas.height = oldHeight * dpr;
ctx.scale(dpr, dpr);

//Perform normal operations ctx.drawImage(this.$refs.cropImg, 0, 0, 250, 400);

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • Vue uses Canvas to generate random sized and non-overlapping circles
  • How to draw the timeline with vue+canvas
  • VUE+Canvas realizes the whole process of a simple Gobang game
  • VUE+Canvas implements the game of God of Wealth receiving ingots
  • How to use VUE and Canvas to implement a Thunder Fighter typing game
  • VUE+Canvas implements the sample code of the desktop pinball brick-breaking game
  • Vue uses the mouse to draw a rectangle on Canvas
  • Vue uses canvas to implement mobile handwritten signature
  • Vue+canvas realizes puzzle game
  • Vue uses canvas handwriting input to recognize Chinese

<<:  VMware installation of Ubuntu 20.04 operating system tutorial diagram

>>:  How to update Ubuntu 20.04 LTS on Windows 10

Recommend

Linux series of commonly used operation and maintenance commands (summary)

Table of contents 1. System monitoring 2. File Op...

A simple example of creating a thin line table in html

Regarding how to create this thin-line table, a s...

How to use shell scripts in node

background During development, we may need some s...

MySQL installation and configuration method graphic tutorial (CentOS7)

1. System environment [root@localhost home]# cat ...

Full-screen drag upload component based on Vue3

This article mainly introduces the full-screen dr...

Vue custom optional time calendar component

This article example shares the specific code of ...

HTML basic summary recommendation (text format)

HTML text formatting tags 標簽 描述 <b> 定義粗體文本 ...

How to use watch listeners in Vue2 and Vue3

watch : listen for data changes (change events of...

How to add a paging navigation bar to the page through Element UI

need Add a paging bar, which can jump to the page...

HTTP return code list (Chinese and English explanation)

http return code list (below is an overview) for ...

MYSQL unlock and lock table introduction

MySQL Lock Overview Compared with other databases...

Full analysis of Vue diff algorithm

Table of contents Preface Vue update view patch s...

Detailed usage of MYSQL row_number() and over() functions

Syntax format: row_number() over(partition by gro...

How to set utf-8 encoding in mysql database

Modify /etc/my.cnf or /etc/mysql/my.cnf file [cli...