Troubleshooting error messages in the console during conversion of image URL to Base64 in AngularJS

While attempting to convert an image URL to Base64 using the FromImageUrl method, I encountered an error in my console.

Access to the image located at '' from the origin 'http://localhost:8383' has been blocked due to CORS policy: The 'Access-Control-Allow-Origin' header is missing from the requested resource. As a result, the origin 'http://localhost:8383' is denied access.

Here is my JavaScript code:

function getBase64FromImageUrl(url) {
            var img = new Image();
            img.setAttribute('crossOrigin', 'Access-Control-Allow-Origin', 'anonymous');

            img.onload = function () {
                var canvas = document.createElement("canvas");
                canvas.width = this.width;
                canvas.height = this.height;
                var ctx = canvas.getContext("2d");
                ctx.drawImage(this, 0, 0);
                $scope.a = canvas.toDataURL("image/png");
            };
            img.src = url;
        }


getBase64FromImageUrl("http://160.114.10.19/voiceapi/Upload/UserProfile/b4d980b3-3e8e-4e26-913e-e79e4ce34f88.png");

Answer №1

If using

img.setAttribute('crossOrigin', 'Anonymous');
does not solve the issue, it may be due to CORS restrictions (attempting to access a resource on a different domain), which can be resolved on the backend. For instance, I attempted to convert 2 images from different websites. The first one did not work, but the second one (from gravatar.com) did. Therefore, the error is not from the JavaScript code itself.

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.height;
    canvas.width = this.width;
    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://vaadin.com/documents/10187/33841/cors-deployment-setup-with-vaadin.png',
  function(dataUrl) {
    console.log('Src static.srcdn.com:', dataUrl)
  }
)

toDataURL(
  'https://www.gravatar.com/avatar/00000000000000000000000000000000?d=monsterid&f=y',
  function(dataUrl) {
    console.log('Src gravatar.com:', dataUrl)
  }
)

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

Issue with Click event not functioning properly following an ajax request in a dynamic element within the Backbone framework

I have successfully implemented a dynamic popup in my Backbone.view through the click of a button: var Section = Backbone.View.extend({ className: 'sqs-frontend-overlay-editor-widget-section', events:{ 'click .sqs--section--control__ed ...

"I am having trouble with req.body in my Express JavaScript application as it is not returning the data from POST requests. Can

Being new to building an express server in NodeJS, I've been able to work on POSTs and GETs using routes and controllers. However, I'm puzzled as to why req.body is showing {} in the terminal. It seems like no data is being received from AJAX. Ca ...

When using jQuery AJAX, the script is returning blank values

Facing a frustrating issue here. I'm sending an AJAX request to a PHP file, but when I check Chrome Network Tools, it doesn't return any JSON data. However, when I try posting the same data using POSTMAN in Chrome, it returns correctly. Also, if ...

Prevent scrolling while popup is open

I found a helpful tutorial online for creating a jQuery popup (). However, due to my limited understanding of jQuery, I'm having trouble getting it to meet my needs. The issues I'm facing are: I need to prevent the webpage from scrolling when ...

How do I adjust brightness and contrast filters on a base64 URL?

When presented with an image in base64 format like this: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABDAAwfqNRk/rjcYX+PxrV/wtWqwJSTlboMgAAAABJRU5ErkJggg== What is the most efficient method to programmatically alter a filter (such as brightness or cont ...

Access and retrieve real-time JavaScript variables directly from a website

Question: I am curious about the possibility of accessing JavaScript variables on a website from C#. Since the scripts are on the client side, is it possible to read their values live through C#? Any assistance or guidance on this matter would be greatly ...

What is the purpose of implementing asynchronous loading for JavaScript in my webpack setup?

I am facing difficulties with handling unusual codes. I am trying to add some query parameters using $.ajaxPrefilter in all jQuery ajax requests. I came across the following code snippet which seems to ensure synchronous loading order, but in my entry.js ...

Tips for resolving the final item issue in Owl Carousel when using right-to-left (RTL)

Encountering a bug with the rtl setting in owl-carousel. When the rtl is applied to the slider and I reach the last item, the entire slider disappears! Here's the code snippet: var viewportWidth = $("body").innerWidth(); if (viewportWidth & ...

Using factories in controllers does not function properly in Angular 1.6

My head is spinning with this one. There are 3 files in play: app.js, app.services.provider.js, admin.js In app.js, I set up my module: (function() { angular.module('myApp', ['ngRoute']).config(function ($routeProvider) { ...

Trouble with Click event not working in Electron and mouse cursor not changing when hovering over an HTML button?

I'm in the midst of a project that involves using the electron framework. Within my project, I have an HTML file, a CSS file, and a Javascript file. The issue at hand is that when I hover over a button, the expected hand pointer icon fails to appear d ...

Insert a 5-second delay in the JavaScript code before triggering the click event on the next button

Currently, I have a JavaScript code in place that is fairly straightforward. The webpage contains about 100 buttons with the class button, and I am successfully simulating clicking each one of them systematically. However, I would like to introduce a dela ...

Vue.js encountered an error while trying to load the component: either the template or render function is not

Currently I am delving into the realm of Vue.js paired with Laravel by following this series, where the narrator seems to breeze through without encountering any errors. Unfortunately, when I attempted to change the route, a pesky error made an appearance. ...

Data loading issue with asp.net mvc Ajax

I am currently facing an issue while attempting to fetch data from the controller using ajax. Controller [HttpGet] public ActionResult GetServices() { var data = _bbdb.ListServices.Where(d => d.Status == true).ToList(); return Json(data, JsonR ...

Leverage angular to dynamically update excel sheet with parsed data

Question: I am currently trying to pull data from a website using Angular and I would like to export this data into an Excel file. Additionally, I want the ability to update this file with more data in the future. Is there a library that can help achieve ...

Validation of AngularJS dropdown selection must be completed before submitting the form

I have a Dropdown list within my form and I want to disable the submit button until an element is selected from the list. Here is my button: <input type="submit" value="Get" ng-disabled="form.$invalid " /> I attempted to implement the solution foun ...

Steps for refreshing a JavaScript function responsible for generating a table

Within the code snippet provided, there is a click event attached to a table row. Upon clicking a row, the script extracts the id value from the first column and triggers a REST call. Subsequently, a new table is constructed using a third-party function ca ...

Using JavaScript onChange event with ModelChoiceField arguments

In my Django project, I have a Students model with various fields. I created a ModelChoiceField form allowing users to select a record from the Students table via a dropdown. forms.py: class StudentChoiceField(forms.Form): students = forms.ModelChoic ...

What could be causing the data toggle feature in my navbar to not work on Bootstrap?

Here is a code snippet to create a simple collapsible navbar with Bootstrap 5 that includes a logout button. However, the data toggle feature for the logout button doesn't seem to work when clicked. Any suggestions on how to fix this? <!DOCTYPE ...

The HTML slideshow is not automatically showing up as intended

I need to make a few adjustments to the picture slideshow on my website. Currently, all the pictures are displayed at once when you first visit the site, and it only turns into a slideshow when you click the scroll arrows. I want it to start as a slideshow ...

Accessing Properties in React.js: A Guide

<Element id="1" onClick={this.runFunction(???)}/> When the onClick event is triggered, I want to execute a different function with the key value "1" as an argument. How can I make this happen? Thank you. ...