Convert the front-end image to base64, and use canvas to compress the image

Table of contents

1. Application scenario of image conversion to base64

2. Image to base64 code

3. Compress the uploaded pictures


1. Application scenario of image conversion to base64

Image conversion to base64 is usually used when users upload images. Its function is to let users see the preview images without being affected by the network.

This is the traditional file transfer process : first, the user selects a picture and uploads it to the server, the server saves and receives it and returns a url address, and then the client takes the url address to request the picture, and finally gets a preview of the picture uploaded by the user. If the process is caused by a bad network, it will greatly affect the user experience.

 This is the upload process of converting images to base64

 When uploading, there is no need to rely on the request of the server, and the conversion is performed directly on the client, using file IO reading, which is not affected by network IO, and is much faster than the network

And if there is a need to edit pictures, do you have to go through the first step again? If the network is not good, it will greatly affect the user experience.

So, the main reason for converting pictures to base64 is to improve user experience

2. Image to base64 code

structure of html

  <!-- 上传图片 -->
  <input type="file">
  <img src="" alt="" id="IMG">

Now for the js code

Just post the code and explain it.

 const IMG = document.getElementById('IMG');
 const ipt = document.querySelector('input');
  ipt.onchange = function () {
    const file = ipt.files[0];
    const reader = new FileReader();
    reader.onload = (e) => {
       IMG.src = e.target.result
    }
    reader.readAsDataURL(file)
  }

The first is to get the input tag and img tag elements. Not much to say, everyone will.

Then listen to the onchange() event of the input input box, and get the file object selected by the user through ipt.files[0].

The core code is the reader.readAsDataURL(file) method, because this method is an asynchronous method, and after reading, you can get a code converted into base64, which is printed like this:

 You can also see the file size after converting to base64

Finally, change the src attribute of the img tag through the assignment method

This is the final effect

After uploading, you can see the preview of the picture instantly, because the reader reading method is not affected by the network, and its speed is much faster than the network 

3. Compress the uploaded pictures

Although this method is very easy to use, if the picture is relatively large, it will become slower and the card will

So you can compress the picture, I use canvas to compress it here

directly on the code

 const ipt = document.querySelector('input');
  const IMG = document.getElementById('IMG');

  ipt.addEventListener('change', function () {
    const file = ipt.files[0];
    const reader = new FileReader();

    reader.onload = function (e) {
      const img = new Image();
      img.src = e.target.result;

      img.onload = function () {
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');

        const maxWidth = 300; // 设置最大宽度
        const maxHeight = 300; // 设置最大高度

        let width = img.width;
        let height = img.height;

        // 如果图片尺寸大于最大宽度或最大高度,则按比例缩放图片
        if (width > maxWidth || height > maxHeight) {
          const ratio = Math.min(maxWidth / width, maxHeight / height);
          width *= ratio;
          height *= ratio;
        }

        canvas.width = width;
        canvas.height = height;

        ctx.drawImage(img, 0, 0, width, height);

        const compressedDataUrl = canvas.toDataURL('image/jpeg', 0.8); // 压缩图片质量为0.8
        console.log(compressedDataUrl);
        IMG.src = compressedDataUrl;
      };
    };

    reader.readAsDataURL(file);
  });

 You can see that the file after uploading this time has been compressed. As for the code, it is actually relatively simple. You can understand it just by looking at the comments in my code.

Summarize:

In fact, the function of using this method is to improve the display speed of the front-end page, that is, to improve the user experience

Guess you like

Origin blog.csdn.net/m0_64642443/article/details/132324343