7

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.

greph
  • 79
  • 1
  • 3
  • I don't think there is any workaround other than sending it back to the server, however [one article](http://blog.import.io/tech-blog/html5-canvas-todataurl-webm-vs-png-vs-jpeg) claims that the quality parameter actually works for PNG. – Derek 朕會功夫 Sep 25 '14 at 23:48
  • Thanks Derek, though I haven't had any luck supplying PNG with a quality parameter yet. This article provides any interesting way to 'step down' images: http://stackoverflow.com/questions/18761404/how-to-scale-images-on-a-html5-canvas-with-better-interpolation – greph Sep 29 '14 at 18:49
  • 1
    PNG is a lossless compression format. You can use compression with jpg or webp but no with pngs. https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/toDataURL – ElChiniNet Dec 10 '15 at 02:54

2 Answers2

3

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).

shyyko.serhiy
  • 486
  • 2
  • 10
1

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.

ArJ
  • 395
  • 5
  • 14
  • also this [link](http://stackoverflow.com/questions/18761404/how-to-scale-images-on-a-html5-canvas-with-better-interpolation?lq=1) for better scale down – ArJ Feb 09 '16 at 07:12