Using Javascript to convert an image to a base64 string when the image fails to load initially

Attempting to convert the image into a base64 string using javascript/angularjs code found on this stacko page, for more detailed code you can refer to this link.

function toDataURL(src, callback, outputFormat) {
  var img = new Image();
  img.crossOrigin = 'Anonymous';
  img.onload = function() {
    var canvas = document.createElement('CANVAS');
    var ctx = canvas.getContext('2d');
    var dataURL;
    canvas.height = this.naturalHeight;
    canvas.width = this.naturalWidth;
    ctx.drawImage(this, 0, 0);
    dataURL = canvas.toDataURL(outputFormat);
    callback(dataURL);
  };
  img.src = src;
  if (img.complete || img.complete === undefined) {
    img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
    img.src = src;
  }
}

toDataURL(
  'https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0',
  function(dataUrl) {
    console.log('RESULT:', dataUrl)
  }
)

The function is called within the controller's initialization, yet the image fails to load at first attempt. However, upon reloading the page or invoking the function again through a button, the image displays properly.

Upon debugging, it appears that only by reaching the last if statement which clears the cache, does the image load successfully. Is this behavior expected since the image loads fine upon the second try?

if (img.complete || img.complete === undefined) {
    img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
    img.src = src;
  }

Upon reaching this point, the process continues to the img.onload and loads the image correctly thereafter.

What could be missing in this scenario? Should there be a delay introduced to wait for the image to load? Any suggestions on making it load later or any other potential solutions?

Answer №1

It dawned on me that I overlooked the functionality of ImgPreview from ui-cropper, which eliminated the need to convert the image. Instead, I simply created a $scope in the view to retrieve the ImgPreview and upload it to the database. Unfortunately, I am unable to share any code snippets at this time.

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

Infinite scroll feature in AngularJS triggers function calls while scrolling up and down

I have incorporated the infinite scroll feature from version 1.1.0 into my project. The scenario involves a table where contents are loaded dynamically as the user scrolls down. A similar implementation can be seen in this example, where data is added to ...

Retrieve information from an API (using RESTful methods) and database (MongoDB) based on the user's input

I've developed an API using Node.js, Express, and MongoDB. Currently, I am retrieving data without sending any specific query. However, on the frontend, there is an input where users can search for recipes. For instance, if a user enters "Today", I sh ...

The $watch feature in AngularJS does not function properly within a directive when a controller is used to update data

I created a custom directive and also have a controller to bind data to the directive. The data is retrieved from the server and bound to the directive. However, I noticed that the data in the directive on the page does not update when I change the scope ...

Issue with webpack ProvidePlugin and vendor bundle: The error "angular.module is not a function"

Currently, my Angular application is compiled into a single bundle using Webpack, including all dependencies and app code in one file. I am trying to split this code into two separate bundles: one for dependencies and one for application code. In my webpa ...

Using Selenium to scroll down to an element until its 'style' changes

I'm in the process of scraping a review page similar to this one. While this specific page has only a few reviews, there are others with a larger volume that require extensive scrolling. Upon observation, I noticed that when the page is not complete ...

The use of an import statement outside a module is not allowed when trying to import a custom NPM library

I created a custom module and uploaded it to NPM, which exports a class. While working on an AWS-CDK Project, I installed this dependency and attempted to import it. However, I encountered the following error during the build process with "cdk synth": Can ...

Obtaining a document through an Anchor Element

I am currently implementing a feature to allow users to download a zip file using an anchor tag. Here's how it's set up: <a href="download/sample.zip">sample.zip</a> When the file exists in the download directory, everything works s ...

Using JSON.parse to convert a JSON list into a JavaScript array is not functioning correctly

By utilizing this function, I am able to fetch a JSON list: $(document).ready(function () { var idContact = @ViewData["IdPhysique"]; var Url = "/Accueil/DonneListeFonctionContact"; $.getJSON(Url, { IdContact: idContact }, function ...

Using Node.js to import modules without the need for assignment

In my recent project, I decided to organize my express application by putting all of my routes in a separate file named routes.js: module.exports = function(server) { // Server represents the Express object server.get('/something', (req, res) ...

The function getoffer does not exist

I am encountering an issue with my factory declaration for Malls. It seems that I am getting the error message get offer is not a function! .controller('confirmCtrl', function($scope,Malls,$stateParams,$log) { $scope.offers = Malls.g ...

Creating a dynamic image gallery with varying image dimensions using JavaScript and Bootstrap

Struggling with aligning an image gallery featuring images of varying sizes? I don't want to set the size programmatically as it may not look good on different screens. The additional challenge is dealing with white spaces between images and not knowi ...

Replace a node package with a custom solution

Within my package.json, I have specified a dependency as "protractor": "2.1.0". This particular package is dependent on another package called "jasminewd2": "0.0.5". The behavior of the jasminewd2 package is something that I want to modify. So, I decided ...

Converting a JavaScript array into PHP using json.stringify technique

I am working with a javascript array of divs: [div#heaolu, div#edu, div#usk, div#lootus, div#heaenergia] Now, I need to send this array to PHP. Here is the JS function: function sendData(){ console.log(sendarray); JSON.stringif ...

Searching for a Mongoose Model by utilizing a field from a separate Schema

Let's say I have two schemas - User and Post. User schema includes an array of post _ids, and the Post schema has an attribute indicating if it is an active post, labeled as is_active. So, the goal is to filter Users who have at least one active post ...

Position the arrow for the jQuery validation engine to the center right

Is there a way to align the arrow in the Right Center position? Alternatively, how can I adjust the TopRight to be in the CenterRight position manually? ...

Invoking Vuex mutation inside an Axios interceptor

Is it possible to trigger a mutation from an interceptor in Vue? Specifically, I want to trigger the logout mutation whenever Axios encounters an http 403 error. I have imported Vuex mutations and mapped them as I usually do, but I am struggling to access ...

What is the best way to use JavaScript to access all child classes and their respective tags of a parent element in an HTML document?

I am in the process of designing a webpage where users can select a dish by checking a checkbox, and then specify the quantity they would like to order. I want to implement a logic where the quantity of a dish only increases when the checkbox for that dish ...

"Utilize jQuery mobile to loop through elements (counting listview items) and make changes

Is there a way to dynamically change all listview counters (locate class ".ui-li-count") by iterating through them? ...

Filtering JSON data by nesting checkboxes in an AngularJS application

Trying to create a nested filter search in Angular with JSON data. Seeking assistance from the community since I am new to this and encountering difficulties. ...

Automatically clear select2 inputs after form submission in Laravel using Livewire

How can I set my barcode scanner to automatically select and clear the search box upon submission? <script> $(document).ready(function() { $('.js-example-basic-single1').select2(); $('.js-example-basic-single1&ap ...