Saving PNG files with FileSaver.js

I am trying to use FileSaver.js to download PNG files that are served from my express application. Files are sent as base64 encoded strings, but when I try to use FileSaver.js to save them, they get corrupted.

This is how I try to save them:

var blob = new Blob([base64encodedString], {type: "data:image/png;base64"}); saveAs(blob, "image.png"); 

I also used this way of saving images, but it does not work if base64encodedString gets too big:

 var download = document.createElement('a'); download.href = 'data:image/png;base64,' + base64encodedString; download.download = 'reddot.png'; download.click(); 

What am I doing wrong with FileSaver.js?

+6
source share
1 answer

I found that you probably want to write it on canvas first.

Press here

 base_image = new Image(); base_image.src = Base64String 

canvas in blob

 var canvas = document.getElementById('YourCanvas'); context = canvas.getContext('2d'); // Draw image within context.drawImage(base_image, 0,0); 

then you can use FileSaver.js to save it

and finally save it

 x_canvas.toBlob(function(blob) { saveAs(blob, "screenshot.png"); }, "image/png"); 

A good fiddle was created for this in this post. Click here for script.

+3
source

All Articles