How to compress .png images when exporting from Canvas using toDataURL ()?

You must create a .png image of ~ 20k size using an HTML5 canvas. Unfortunately, when creating .png using the toDataURL () method, you cannot specify quality as you can with jpeg.

Any ideas for a workaround? toDataURL seems to be the only way to generate images from Canvas, and the canvas seems to be the best tool for processing images without interacting with the server. Appreciate any suggestions.

+5
source share
2 answers

There is a way to compress compressed PNG images using the lossless process zlib deflate http://www.w3.org/TR/PNG-Compression.html . There is a library ( https://github.com/ShyykoSerhiy/canvas-png-compression ) that provides a pad for HTMLCanvasElement.toDataURL () when the image type is "image / png" and allows you to provide "quality" as the second parameter for HTMLCanvasElement.toDataURL () for png.

NOTE that it provides better results (smaller size) only in Chrome. Sometimes Firefox has better compression than canvas-png compression (as for version 0.0.3).

+2
source

You can do something by reducing it and then scaling it again.

  • Zoom out by drawing it on a smaller canvas, then get the data url.

  • Creating an image object sets the data URL as the source.

  • Draw the original canvas using this img object (obviously inside the onload event callback)

  • Find the canvas aspect ratio to give you the best result by experimenting a bit.

+1
source

Source: https://habr.com/ru/post/1203438/


All Articles