尝试使用HTML5文件系统将canvas PNG数据url保存到磁盘,但是当我检索为URL时,它无效 [英] Trying to save canvas PNG data url to disk with HTML5 filesystem, but when I retrieve as URL, it's invalid

查看:127
本文介绍了尝试使用HTML5文件系统将canvas PNG数据url保存到磁盘,但是当我检索为URL时,它无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从画布上获取base64编码的图像为:

I get the base64-encoded image form the canvas as:

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

我尝试将其设置为像这样的图像的src:

I try to set it as src of an image like this:

document.getElementById( "saved" ).src = event.toURL();

这将写入文件,并且我能够找到它并获得一个url(通过读取它并使用事件: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?

推荐答案

data是字符串,因此当您将其传递给blob时,二进制数据将是采用UTF-8编码的字符串.你要 二进制数据不是字符串.

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.

您可以这样做:

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中不可用.

There is also canvas.toBlob available in future but not currently in Chrome.

演示 http://jsfiddle.net/GaLRS/

这篇关于尝试使用HTML5文件系统将canvas PNG数据url保存到磁盘,但是当我检索为URL时,它无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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