我从画布中得到base64编码的图像:
var dataURL = canvas.toDataURL( "image/png" );
然后我把它变成这样的数据:
//Remove the beginning identifier and use Chrome/Firefox?safari built int base64Decoder
var data = atob( dataURL.substring( "data:image/png;base64,".length ) );
然后我通过以下方式将其写入文件系统:
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 );
}
}
我尝试将其设置为图像的src,如下所示:
document.getElementById( "saved" ).src = event.toURL();
写入文件并且我能够找到它并获取网址(通过阅读并使用事件:event.toURL()
。但图像在网页上显示为图像损坏图标。我是什么人做错了?
答案 0 :(得分:23)
data
是一个字符串,因此当您将其传递给blob时,二进制数据将是UTF-8编码的字符串。你要
二进制数据不是字符串。
你可以这样做:
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"} );
将来还有canvas.toBlob
可用,但目前不在Chrome中。