Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Need to generate .png images that are about ~20k in size using HTML5 canvas. Unfortunately, when creating .pngs using the toDataURL() method, you cannot specify quality like you can with jpegs.

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

like image 639
greph Avatar asked Sep 25 '14 22:09

greph


People also ask

What is canvas toDataURL ()?

toDataURL() method returns a data URL containing a representation of the image in the format specified by the type parameter. The desired file format and image quality may be specified. If the file format is not specified, or if the given format is not supported, then the data will be exported as image/png .

How do I compress a PNG file in Linux?

pngquant can help you to reduce the size of a PNG image in Linux by performing lossy and lossless compression. pngquant usually is the best option as it seems to optimize the file size the most without sacrificing much on quality. First, Install pngquant package for your system.


2 Answers

There IS a way to have compression for PNG images using lossless zlib deflate process http://www.w3.org/TR/PNG-Compression.html . There is a library (https://github.com/ShyykoSerhiy/canvas-png-compression) that provides shim for HTMLCanvasElement.toDataURL() when image type is 'image/png' and enables ability to provide 'quality' as second parameter to HTMLCanvasElement.toDataURL() for png.

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

like image 197
shyyko.serhiy Avatar answered Oct 20 '22 13:10

shyyko.serhiy


You can do something by scaling it down and then scaling it up again.

  • Scale down by drawing it on a smaller canvas, then get the data url.

  • Create an image object set the data url as its source.

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

  • Find the size ratio of the canvases to give you optimum result by experimenting a bit.

like image 34
ArJ Avatar answered Oct 20 '22 15:10

ArJ