Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8211277
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 7, 20262026-06-07T10:22:34+00:00 2026-06-07T10:22:34+00:00

Android does not allow native apps like Phonegap-based apps to write binary files. A

  • 0

Android does not allow native apps like Phonegap-based apps to write binary files. A common application is converting Base64 Strings to Images. So, how do you go about this problem?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-07T10:22:36+00:00Added an answer on June 7, 2026 at 10:22 am

    The solution; This plugin that converts a Base64 PNG String and generates an image to the sdCard. Let’s go!

    1. The Base64 Decoder

    Get this blazing fast Base64 encode/decoder class called MiGBase64. Download it from SourceForge. Create a folder called ‘util’ within your project’s src/ folder. Place the downloaded class there.

    2. The java

    Create a folder called ‘org/apache/cordova’ within your project’s src/ folder.
    Create in it a Java file called “Base64ToPNG.java” with the following source code.

    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

    Write this JavaScript as Base64ToPNG.js to your project’s www folder. DONT forget to include a reference to it in your html files.

    /**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

    Add the following to res/xml/plugins.xml file

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

    5. Finally, HTML examples and the parameters

    <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. By default the same as the one in url.
    2. folder: Name of the directory to generate the file to. By default “sdcard/Pictures”
    3. overwrite: If the file already exists, replace it. By default false.

      I hope this answers some bothering questions. Happy coding!

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

It seems the java.net.NetworkInterface implementation of android does not have a byte[] getHardwareAddress() method
The Android Developer documentation does not mention whether the method below (and similar ones)
Android Emulator Icon in windows 7 does not show in TaskBar..see my Image... I
-webkit-device-pixel-ratio query is supported by both iOS and Android but since iOS does not
I just defined a dialog as android site suggest, but it does not show
How to make spinner to fill empty place in left side? android:layout_width=fill_parent does not
Does Android support virtual memory concept? I read it does use paging but not
Does someone have the source for Android loadable kernel module for libnfc? If not,
Does anyone know if there is a google goggles API for Android? If not,
Provided utility looks bad, for example it does not allow to do Save As,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.