Home  >  Q&A  >  body text

javascript - What is the principle of canvas compressing images?

The toDataURL method in canvas can specify the format and compression quality of the image after compression, for example, compress it into webp format:

canvas.toDataURL('image/webp',quality);

toDataURL uses base64 to encode the image, and the encoded source file is 33% larger than before encoding, refer to the address, but the quality parameter can specify the compression quality, the closer the compression quality is to 0, The stronger the image compression.

Question 1: Using base64 encoding to enlarge the image source file, can base64 compress the image?

Question 2: Is encoding small images with base64 just to reduce http requests?

Question 3: What is the principle of compressing images using the toDataURL method in canvas? What exactly does the quality parameter do?

给我你的怀抱给我你的怀抱2659 days ago1065

reply all(2)I'll reply

  • 滿天的星座

    滿天的星座2017-06-26 10:57:55

    base64 only converts the binary code corresponding to the image according to the rule that six bits correspond to one character. After transcoding, the file is larger than the original image file. However, for small images, the extra bytes transmitted after conversion are far less expensive than establishing an additional http connection, so base64 is used to transcode the small images to improve page loading speed.
    As for the principle of image compression, to put it simply, the color difference on a picture is reduced through algorithms, sacrificing picture quality. For example, the color information of four pixels with similar colors occupies about 16 bytes before compression. After compression, it can be reduced by nearly 4 times when converted into one color. Quality is used to control the intensity of color difference. The smaller the value, the greater the intensity. Two pixels with a large color difference will also be processed. Naturally, after being compressed, the file will be smaller and the image quality will be worse

    reply
    0
  • 黄舟

    黄舟2017-06-26 10:57:55

    1. No way

    2. is

    3. Control the quality of the image encoding format. For example, webp can perform lossy compression. The higher the quality, the smaller the loss and the larger the file size.

    reply
    0
  • Cancelreply