使用FileSaver.js保存PNG文件 [英] Saving PNG files with FileSaver.js

查看:980
本文介绍了使用FileSaver.js保存PNG文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用FileSaver.js下载从我的快递应用程序提供的PNG文件。这些文件是作为base64编码的字符串发送的,但是当我尝试使用FileSaver.js来保存它们时,它们就会被破坏。

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");

我也使用这种保存图像的方法,但是如果base64encodedString它不起作用变得太大了:

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();

FileSaver.js我做错了什么?

What am I doing wrong with the FileSaver.js?

推荐答案

我发现你可能想先将它写入Canvas。

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

点击此处

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

canvas in blob

canvas into a blob

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

然后你可以使用FileSaver.js保存它

then you can use FileSaver.js to 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

这篇关于使用FileSaver.js保存PNG文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆