Convert from Base64 String to PNG File

10,634

Solution 1

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.

Solution 2

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/

Share:
10,634
Seany84
Author by

Seany84

Updated on June 04, 2022

Comments

  • Seany84
    Seany84 almost 2 years

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

    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.

    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:

    writer.write(filedata);