javascript 从 Base64 字符串转换为 PNG 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9840742/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 07:59:56  来源:igfitidea点击:

Convert from Base64 String to PNG File

javascripthtmlcordova

提问by Seany84

I am trying to convert a base64 encoded string to an image object using the method below.

我正在尝试使用以下方法将 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');
}

The line:

线路:

Signaturebase64 = cb_canvas.toDataURL();

Works as expected and gives me back my base64 string.

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

What I would like to do now is to convert it to an image file on the phone's persistent storage.

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

The following line is writing the base64 string to the storage but what I want it to do is save it as a PNG file instead:

以下行将 base64 字符串写入存储,但我希望它做的是将其另存为 PNG 文件:

writer.write(filedata);

采纳答案by Simon MacDonald

You can't use the PhoneGap FileWriter to write binary data. You'd need to write a plugin to send your base64 encoded data to the native side, encode it into binary then write it using native code.

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

回答by Petteri Hietavirta

You need to decode the base64 back to binary. Here is an example: http://blog.danguer.com/2011/10/24/base64-binary-decoding-in-javascript/

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