简体   繁体   English

Phonegap插件:如何在Android中将Base64字符串转换为PNG图像

[英]Phonegap Plugin:How to convert Base64 String to a PNG image in Android

Android does not allow native apps like Phonegap-based apps to write binary files. Android不允许基于Phonegap的应用程序等本机应用程序编写二进制文件。 A common application is converting Base64 Strings to Images. 常见的应用程序是将Base64字符串转换为图像。 So, how do you go about this problem? 那么,你怎么解决这个问题呢?

The solution; 解决方案; This plugin that converts a Base64 PNG String and generates an image to the sdCard. 此插件转换Base64 PNG字符串并生成图像到sdCard。 Let's go! 我们走吧!

1. The Base64 Decoder 1. Base64解码器

Get this blazing fast Base64 encode/decoder class called MiGBase64. 获得这个名为MiGBase64的超快速Base64编码/解码器类。 Download it from SourceForge . SourceForge下载它。 Create a folder called 'util' within your project's src/ folder. 在项目的src /文件夹中创建一个名为“util”的文件夹。 Place the downloaded class there. 将下载的课程放在那里。

2. The java 2. java

Create a folder called 'org/apache/cordova' within your project's src/ folder. 在项目的src /文件夹中创建一个名为“org / apache / cordova”的文件夹。 Create in it a Java file called "Base64ToPNG.java" with the following source code. 使用以下源代码在其中创建名为“Base64ToPNG.java”的Java文件。

package org.apache.cordova;

/**
* A phonegap plugin that converts a Base64 String to a PNG file.
*
* @author mcaesar
* @lincese MIT.
*/

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;

import android.os.Environment;
import java.io.*;
import org.json.JSONException;
import org.json.JSONObject;
import util.Base64;

public class Base64ToPNG extends Plugin {

    @Override
    public PluginResult execute(String action, JSONArray args, String callbackId) {

        if (!action.equals("saveImage")) {
            return new PluginResult(PluginResult.Status.INVALID_ACTION);
        }

        try {

            String b64String = "";
            if (b64String.startsWith("data:image")) {
                b64String = args.getString(0).substring(21);
            } else {
                b64String = args.getString(0);
            }
            JSONObject params = args.getJSONObject(1);

            //Optional parameter
            String filename = params.has("filename")
                    ? params.getString("filename")
                    : "b64Image_" + System.currentTimeMillis() + ".png";

            String folder = params.has("folder")
                    ? params.getString("folder")
                    : Environment.getExternalStorageDirectory() + "/Pictures";

            Boolean overwrite = params.has("overwrite") 
                    ? params.getBoolean("overwrite") 
                    : false;

            return this.saveImage(b64String, filename, folder, overwrite, callbackId);

        } catch (JSONException e) {

            e.printStackTrace();
            return new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage());

        } catch (InterruptedException e) {
            e.printStackTrace();
            return new PluginResult(PluginResult.Status.ERROR, e.getMessage());
        }

    }

    private PluginResult saveImage(String b64String, String fileName, String dirName, Boolean overwrite, String callbackId) throws InterruptedException, JSONException {

        try {

            //Directory and File
            File dir = new File(dirName);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File file = new File(dirName, fileName);

            //Avoid overwriting a file
            if (!overwrite && file.exists()) {
                return new PluginResult(PluginResult.Status.OK, "File already exists!");
            }

            //Decode Base64 back to Binary format
            byte[] decodedBytes = Base64.decode(b64String.getBytes());

            //Save Binary file to phone
            file.createNewFile();
            FileOutputStream fOut = new FileOutputStream(file);
            fOut.write(decodedBytes);
            fOut.close();


            return new PluginResult(PluginResult.Status.OK, "Saved successfully!");

        } catch (FileNotFoundException e) {
            return new PluginResult(PluginResult.Status.ERROR, "File not Found!");
        } catch (IOException e) {
            return new PluginResult(PluginResult.Status.ERROR, e.getMessage());
        }

    }
}

3. The Javascript 3. Javascript

Write this JavaScript as Base64ToPNG.js to your project's www folder. 将此JavaScript编写为Base64ToPNG.js到项目的www文件夹中。 DONT forget to include a reference to it in your html files. 不要忘记在你的html文件中包含对它的引用。

/**Works on all versions prior and including Cordova 1.6.1 
* by mcaesar
*  MIT license
*  
*/

(function() {
    /* This increases plugin compatibility */
    var cordovaRef = window.PhoneGap || window.Cordova || window.cordova; // old to new fallbacks

    /**
    * The Java to JavaScript Gateway 'magic' class 
    */
    function Base64ToPNG() { }

    /**
    * Save the base64 String as a PNG file to the user's Photo Library
    */
    Base64ToPNG.prototype.saveImage = function(b64String, params, win, fail) {
        cordovaRef.exec(win, fail, "Base64ToPNG", "saveImage", [b64String, params]);
    };

    cordovaRef.addConstructor(function() {
        if (!window.plugins) {
            window.plugins = {};
        }
        if (!window.plugins.base64ToPNG) {
            window.plugins.base64ToPNG = new Base64ToPNG();
        }
    });

})(); 

4. The plugins.xml file 4. plugins.xml文件

Add the following to res/xml/plugins.xml file 将以下内容添加到res / xml / plugins.xml文件中

<plugin name="Base64ToPNG" value="org.apache.cordova.Base64ToPNG"/>

5. Finally, HTML examples and the parameters 5.最后,HTML示例和参数

<button onclick="test();">No optional params required, Cowboy.</button> </br>
<button onclick="test2();">Make PNG with some parameters</button>

<script src="Base64ToPNG.js" type="text/javascript"></script>

<script type="text/javascript">

//May have a mime-type definition or not 
var myBase64 = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="//a red dot


function test(){

    //Illustrates how to use plugin with no optional parameters. Just the base64 Image.
    window.plugins.base64ToPNG.saveImage(myBase64, {}, 
       function(result) {
          alert(result);
       }, function(error) {
          alert(error);
       });
 }

 //No mimetype definition example
 var myOtherBase64 = "iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="

 function test2(){

    //Shows how to use optional parameters
    window.plugins.base64ToPNG.saveImage(myBase64, {filename:"dot.png", overwrite: true}, 
       function(result) {
          alert(result);
       }, function(error) {
          alert(error);
    });

 }
 </script>

Parameters 参数

  1. filename : Name of the file to be generated. filename :要生成的文件的名称。 By default the same as the one in url. 默认情况下与url中的相同。
  2. folder : Name of the directory to generate the file to. folder :要生成文件的目录的名称。 By default "sdcard/Pictures" 默认情况下“sdcard / Pictures”
  3. overwrite : If the file already exists, replace it. 覆盖 :如果文件已存在,请将其替换。 By default false. 默认为false。

    I hope this answers some bothering questions. 我希望这能解决一些令人烦恼的问题。 Happy coding! 快乐的编码!

Fo anybody wanting to use this with kineticjs, the following works a treat: 任何想要与kineticjs一起使用的人,以下是一种享受:

function saveCanvas() {
    $('#save').bind( $bind, function(){
        stage.toDataURL({
        callback: function(dataUrl){
            window.plugins.base64ToPNG.saveImage(dataUrl.substr(22,dataUrl.length), {}, 
                function(result) {
                    alert(result);
                }, function(error) {
                    alert(error);
                }
            );
        },
            mimeType: 'image/png',
            quality: 0.5
        });
    });
}

This solution only works when feeding it a CLEAN Base64 string. 此解决方案仅在为CLEAN Base64字符串提供时才有效。 In other words, the "data:image/png;base64," part should be removed or the Base64 decoder fill fail, causing a nullpointer error when writing the file. 换句话说,应该删除“data:image / png; base64”部分或者Base64解码器填充失败,从而在写入文件时导致nullpointer错误。

Also I noticed that the image does not show up in the Gallery but it is stored correctly on the SD card. 另外我注意到图像没有显示在图库中,但它正确存储在SD卡上。 When I download it to my PC I can open it just fine. 当我将它下载到我的电脑时,我可以打开它。 Not sure what that is about. 不知道那是什么。

Thanks for the work! 谢谢你的工作!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM