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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With