Creating an image file from a base64 string in Phonegap

I am currently developing a phonegap application for Android and encountered an issue while trying to save a base64 PNG string as a file. Upon opening the file, I realized that the string is simply saved and cannot be viewed as an image.

My goal is to find a way to generate and save an actual image from the base64 string. Below is the code snippet I have been working with:

The JavaScript Code (Formatted 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); //the image does not open
}

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

I attempted to modify the code to only save the image data, but it also did not yield the desired result. (Refer to the modified code below)

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

The HTML Triggering Function:

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

Your assistance in resolving this matter would be greatly appreciated. Thank you.

Answer №1

To display the image, simply assign the base 64 data to the src attribute of your image element.

var picture = document.getElementById('imageID');
picture.src = "data:image/jpeg;base64," + imageData;

Answer №2

Don't worry about replacing the base64 string, simply convert the string using the steps below:

If using javascript:

var pic = document.getElementById('imageData');
pic.src = convertedString;// this will convert the data

If using jquery:

$("#pictureID").attr("src", convertedString)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unlocking protection: Confirming password strength and security with password indicator and regular expressions for special characters in angular through directive

I have developed an app for password validation using an AngularJS directive. The requirements for the password include at least one special character, one capital letter, one number, and a minimum length of 8 characters. Additionally, I have included a pa ...

Navigate to a different page while the AJAX request is awaiting a response

My webpage performs several ajax calls that usually take about a minute to complete. Unfortunately, while these calls are still processing, my browser waits for them to finish before allowing me to navigate to another page. What I want is for the ajax call ...

Animating range tick movements as the range thumb moves

My custom range input includes a span that displays the range's value and a div with multiple p elements acting as ticks. To create these ticks, I had to use a custom div because using "appearance: none" on the range hides the ticks by default. The ti ...

Exploring the concept of global objects within the expressjs framework

Currently, I am working on building a school management system. One issue I encountered is related to the creation of global objects in my backend when a teacher sends a post request. I am wondering whether multiple teachers accessing the server will res ...

How should a JavaScript object be properly formatted?

Recently, I created a project using ng-repeat with AngularJS 1.x, and it was smooth sailing. JavaScript: var app = angular.module('myModule', []); app.controller('myController', function() { this.dishes = [ { 'name&a ...

Tips for retrieving values from CheckBox in Asp.net MVC using Jquery

I'm currently facing a dilemma while working on an MVC web application. I have dynamically generated checkboxes from my database, but I am uncertain about how to extract the value of the selected checkbox and store it in the database. Any suggestions? ...

Tips for inserting a placeholder into an input field using the field's unique ID with JavaScript

I am looking to dynamically add a placeholder to an input field using JavaScript based on the field's ID. The form fields have been created with a WordPress plugin, but I cannot locate the file or folder where the code is located. Can anyone assist me ...

The Truffle test encounters an issue: "Error: Trying to execute a transaction that calls a contract function, but the recipient address ___ is not a contract address."

Every time I run truffle test in the terminal, I encounter the following error message: Error: Attempting to run a transaction which calls a contract function, but the recipient address 0x3ad2c00512808bd7fafa6dce844a583621f3df87 is not a contract address. ...

div sliding inside another div sliding

I have implemented a sliding content feature where you click on the menu at the top and the content below slides to the next "li". Interestingly, within the last link on the main menu titled "replacement filters," there is another sliding content embedded ...

Submitting forms with Ajax without reloading the page can cause errors in Internet Explorer

Simply put: Upon clicking the login button in Firefox, Chrome, or Safari, the form is submitted correctly, running a validation via ajax and opening a new page. However, in Internet Explorer (version less than 9), the submission attempts to post to the c ...

Incorporate `swagger-ui-express` and `swagger-jsdoc` into your workflow both pre- and post-typescript compilation for optimal

In my project using TypeScript, path mapping, and esbuild for transpiling, I am trying to make both packages in the title work together. The swagger does not seem to work with the transpiled code. To transpile, I use the command rimraf dist && esbu ...

Angular: Keeping all FormControls in sync with model updates

I am dealing with a collection of FormControls that were created using FormBuilder: this.someForm = this.fb.group({ name: '', size: '', price: '', }); Is there an alternative method to update them based on ...

Issues with arrays and objects not functioning properly in local storage

Currently, I am working on implementing a TODO list that utilizes local storage to store data. Unfortunately, I have encountered an issue in my code that I am struggling to fix. In the getTaskArray() function, I retrieve an array from local storage using ...

Navigating with buttons in React JS

In my material-ui, I have a button set up like this: <Button style={green} raised="true" label="Continue to create group"}> CREATE NEW GROUP </Button> I am looking to make it so that when the button is clicked, it will take me ...

Utilizing React hooks to capture the checkbox value upon change and transfer it to the submitForm function

I've got a functioning hook that monitors the onChange event of input fields, then spreads them into a variable and sends them to a Lambda function for sending an email with SendGrid. Everything is working fine. However, when I add an input type of c ...

What is the reason behind the success of one method for setting the date, while the other method fails to work?

For both scenarios, the specific date I want to configure in this instance is 1395227280627 in milliseconds and 3/19/2014 12:08:00 PM in human-readable form. 1) The initial approach, which is incorrect, is as follows: Calendar ret1=GregorianCalendar.getI ...

Troubleshooting Azure typescript function: Entry point for function cannot be determined

project structure: <root-directory> ├── README.md ├── dist ├── bin ├── dependencies ├── host.json ├── local.settings.json ├── node_modules ├── package-lock.json ├── package.json ├── sealwork ...

Solving Unique Data Types Directly in the Root of GraphQL

It seems like there's an obvious solution missing. I have IDs stored as [String] that I need to resolve to their corresponding full objects. Context This is the functionality I aim to achieve, but the crucial aspect missing is the resolvers: const ...

The code is nearly identical except for one issue that causes an infinite loop within useEffect

Hey, I'm new to reactjs and I've encountered a puzzling situation with the following two code snippets. I can't figure out why using the "First code" results in an infinite loop (endless '123' log outs in my browser console) while ...

Using PHP to calculate the total number of records within an HTML document

I am currently working on a PHP script to establish a connection with my MySQL database in order to retrieve the total number of users registered on my forum by counting the records in the table. https://i.sstatic.net/ZR0IY.png The PHP script should disp ...