【问题标题】:Convert from Base64 String to PNG File从 Base64 字符串转换为 PNG 文件
【发布时间】:2012-03-23 22:58:46
【问题描述】:

我正在尝试使用以下方法将 base64 编码的字符串转换为图像对象。

function gotFileWriter(writer) {
    console.log('Starting gotFileWriter');
    writer.onwrite = function (evt) {
        console.log("write success");
    };

    $.mobile.showPageLoadingMsg();
    //        console.log('height: ' + cb_canvas.height);
    //        console.log('width: ' + cb_canvas.width);
    Signaturebase64 = cb_canvas.toDataURL();

    //I need to save the base64 string to a PNG image on the Phone here.  
    writer.write(Signaturebase64 );

    $.mobile.hidePageLoadingMsg();
    $.mobile.changePage("#MyJob");
    console.log('Finished gotFileWriter');
}

行:

Signaturebase64 = cb_canvas.toDataURL();

按预期工作并返回我的 base64 字符串。

我现在想做的是将其转换为手机永久存储上的图像文件。

以下行正在将 base64 字符串写入存储,但我想要它做的是将其保存为 PNG 文件:

writer.write(filedata);

【问题讨论】:

  • 如果base64字符串只是编码后的图片数据,直接解码后写入带有图片扩展名的文件即可。

标签: javascript html cordova


【解决方案1】:

您需要将 base64 解码回二进制。这是一个例子:http://blog.danguer.com/2011/10/24/base64-binary-decoding-in-javascript/

【讨论】:

    【解决方案2】:

    您不能使用 PhoneGap FileWriter 写入二进制数据。您需要编写一个插件将您的 base64 编码数据发送到本机端,将其编码为二进制,然后使用本机代码编写。

    【讨论】:

    • 感谢您的回复。你有类似的链接或教程吗?
    • 查看插件信息:wiki.phonegap.com/w/page/36752779/PhoneGap%20Plugins 还可以查看 phonegap 源代码,了解我们是如何编写文件的,您可以在编写之前添加一些代码来进行 base64 解码。
    • 谢谢西蒙,我会在星期一告诉你我的进展情况。
    • @SimonMacDonald 我尝试过使用writer.write(atob(IM.fileReceived));,其中IM.fileReceived 是我的图像编码字符串,但写入文件后我无法查看它,你能告诉我我在哪里错了
    猜你喜欢
    • 2020-02-24
    • 2021-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-01
    相关资源
    最近更新 更多