javascript 尝试使用 HTML5 文件系统将画布 PNG 数据 url 保存到磁盘,但是当我检索为 URL 时,它无效
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17332071/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Trying to save canvas PNG data url to disk with HTML5 filesystem, but when I retrieve as URL, it's invalid
提问by Don Rhummy
I get the base64-encoded image form the canvas as:
我从画布中得到 base64 编码的图像:
var dataURL = canvas.toDataURL( "image/png" );
Then I turn it into data like this:
然后我把它变成这样的数据:
//Remove the beginning identifier and use Chrome/Firefox?safari built int base64Decoder
var data = atob( dataURL.substring( "data:image/png;base64,".length ) );
Then I write it to the filesystem via:
然后我通过以下方式将其写入文件系统:
event.createWriter(
function(writerEvent)
{
//The success handler
writerEvent.onwriteend = function(finishEvent)
{
...
};
//Error handler
writerEvent.onerror = settings.error;
// Create a new Blob
var blob = new Blob( [ data ], { type: "image/png" } );
//Write it into the path
writerEvent.write( blob );
}
}
I try to set it as src of an image like this:
我尝试将其设置为这样的图像的 src:
document.getElementById( "saved" ).src = event.toURL();
That writes the file and I am able to find it and get a url (by reading it and using the event: event.toURL()
. But the image shows as a broken image icon on the web page. What am I doing wrong?
这会写入文件,我能够找到它并获得一个 url(通过阅读它并使用事件:event.toURL()
。但是图像在网页上显示为损坏的图像图标。我做错了什么?
回答by Esailija
data
is a string, so when you pass it to blob, the binary data will be that string in UTF-8 encoding. You want
binary data not a string.
data
是一个字符串,所以当你将它传递给 blob 时,二进制数据将是 UTF-8 编码的字符串。您想要二进制数据而不是字符串。
You can do it like:
你可以这样做:
var canvas = document.createElement("canvas");
var dataURL = canvas.toDataURL( "image/png" );
var data = atob( dataURL.substring( "data:image/png;base64,".length ) ),
asArray = new Uint8Array(data.length);
for( var i = 0, len = data.length; i < len; ++i ) {
asArray[i] = data.charCodeAt(i);
}
var blob = new Blob( [ asArray.buffer ], {type: "image/png"} );
There is also canvas.toBlob
available in future but not currently in Chrome.
canvas.toBlob
将来也可以使用,但目前在 Chrome 中不可用。