Search code examples
javascripthtmlcanvaspngtodataurl

How to use toDataURL to set as PNG8?


Pretty simple question but I can't find documentation anywhere. How do I tell canvas.toDataURL() to save the file as a PNG-8?

thumbnail = canvas.toDataURL();

I know I could pass "image/jpeg" to get a jpeg, but how about a PNG-8?


Solution

  • There is no common builtin method to produce palette-indexed PNGs in any of the major browsers today. The browsers are only required to support basic PNG 24-bit bitmap and alpha.

    Though, they are free to support any additional format they desire but it's unlikely they will move too much away from what is cross-browser compatible (some exceptions exist but is not used much such as TIFF in Safari, ICO in Firefox).

    For this to work today however you would need to extract the pixels, quantize the colors into a palette, then compile the file, format the bitmap, encode it and compress it - then save it out. It's doable but it's a project on its own.

    Optionally look into services such as TinyPNG [I'm not affiliated]. They provide an API which can be used to programmatically send your ordinary PNGs and have minimized PNGs returned, usually meaning "PNG8".