How to save a PNG in a JavaScript string to disk?

Sometimes, we want to save a PNG in a JavaScript string to disk.

In this article, we’ll look at how to save a PNG in a JavaScript string to disk.

How to save a PNG in a JavaScript string to disk?

To save a PNG in a JavaScript string to disk, we can create an anchor element, set the href property to the base64 PNG image string, then call click to download the image.

For instance, we write:

const download = document.createElement('a');
download.href = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';
download.download = 'reddot.png';
download.click();

to call document.createElement to create an anchor element.

Then we set download.href to the base64 PNG image string.

Next, we set download.download to the file name we want to save the file as.

Finally, we call click to download the file.

Conclusion

To save a PNG in a JavaScript string to disk, we can create an anchor element, set the href property to the base64 PNG image string, then call click to download the image.