html5-canvaspngtodataurl

Cannot open PNGs created with canvas.toDataUrl


I create a png blob from a canvas with the toDataUrl method.

const pngdata = canvas.toDataURL("image/png");

I open a text editor and copy the content of pngdata into a file that I call img.png

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAkMAAAiICAYAAAD...

I save this file. When I try to open it (Windows 10) I get "It looks like we don't support this file format"

Removing data:image/png;base64, from the file doesnt help

Why does this not work?


Solution

  • Because your file is still encoded as Base64. You need to decode it to actual binary data for it to be a correct binary file.

    You can find many online tools that will do this for you, or the best is probably to directly export your canvas drawing to a binary Blob and download this Blob thanks to a blob:// URL.