Saving PNG files with FileSaver.js

[亡魂溺海] 提交于 2019-12-19 02:02:11

问题


I'm trying to use FileSaver.js to download PNG files that are being served from my express app. The files are being sent as base64 encoded strings, but when I try to use FileSaver.js to save them they become corrupted.

This is the way I'm trying to save them:

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

I've also used this method of saving the images, but it doesn't work if the base64encodedString becomes too large:

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

What am I doing wrong with the FileSaver.js?


回答1:


I've found that you'll probably want to write it to a Canvas first.

Click Here

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

canvas into a 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 nice fiddle was also created for this in that post Click Here For Fiddle



来源:https://stackoverflow.com/questions/33242959/saving-png-files-with-filesaver-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!