Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Phonegap - How to generate image file from base64 string?

Am writing a phonegap app for Android and at one point, I save a base64 PNG string as a file. However, I have observed that the string is just dumped into a file and can't be viewed as an image when opened.

I'd like to be able to save an image generated from the base64 string.This is what I have:

The Javascript (Formated for Phonegap):

/*** Saving The Pic ***/
var dataURL = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="; //A simple red dot

function gotFS(fileSystem) {
    fileSystem.root.getFile("dot.png", {create: true, exclusive: false}, gotFileEntry, fail);
}

function gotFileEntry(fileEntry) {  
    fileEntry.createWriter(gotFileWriter, fail);
}

function gotFileWriter(writer) {
    writer.write(dataURL); //does not open as image
}

function fail(error) {
    console.log(error.code);
}

I tried editing the code to save just the image data but it did't work either. (See below)

function gotFileWriter(writer) {
     var justTheData = dataURL.replace(/^data:image\/(png|jpg);base64,/, "");//Removes everything up to ...'base64,'
     writer.write(justTheData); //also does not show
 }

The HTML that triggers everthing:

<p onclick="window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail)">Save a Dot</p>

Please help. Thank you.

like image 573
mukama Avatar asked Jul 04 '12 01:07

mukama


1 Answers

You just need to set the src of your image to the base 64 data to view the image.

var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + justTheData;
like image 62
Simon MacDonald Avatar answered Oct 04 '22 04:10

Simon MacDonald