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

2

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.

Assibilate answered 25/9, 2014 at 22:51 Comment(3)
I don't think there is any workaround other than sending it back to the server, however one article claims that the quality parameter actually works for PNG.Blouse
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: #18761904Assibilate
PNG is a lossless compression format. You can use compression with jpg or webp but no with pngs. developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/…Odiliaodille
H
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).

Hit answered 13/12, 2015 at 22:51 Comment(0)
C
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.

Cherisecherish answered 8/2, 2016 at 20:11 Comment(1)
also this link for better scale downCherisecherish

© 2022 - 2024 — McMap. All rights reserved.