Transforming an Image URL into base64 format using Angular

I'm currently facing difficulty when attempting to convert a specified image URL into base64. In my scenario, I have a string that represents the image's path.

var imgUrl = `./assets/logoEmpresas/${empresa.logoUrl}`

Is there a way to directly convert the provided image URL into base64? I have already tried referring to this particular discussion.

Converting an image to base64 in angular 2

However, it seems that the mentioned discussion focuses on obtaining the image from a form... How can I modify it to suit my case?

Answer №1

If you ever need to convert an image to base64, this code snippet will come in handy.

async function fetchImageConvertToBase64(imageUrl) {
  var response = await fetch(imageUrl);
  var blob = await response.blob();

  return new Promise((resolve, reject) => {
    var reader  = new FileReader();
    reader.addEventListener("load", function () {
        resolve(reader.result);
    }, false);

    reader.onerror = () => {
      return reject(this);
    };
    reader.readAsDataURL(blob);
  })
}

Simply use the function like this:

fetchImageConvertToBase64('your image url')
    .then(result => displayImage.src = result)
    .catch(err => console.error(err));

Answer №2

This code snippet works seamlessly with pdfMake and angular applications

You have the ability to utilize this function for generating a base64 image

    convertToDataURL = async (imageUrl) => {
    console.log("Downloading image...");
    var response = await fetch(imageUrl);
    var imageData = await response.blob();

    const resultData = await new Promise((resolve, reject) => {
      var reader = new FileReader();
      reader.addEventListener("load", function () {
        resolve(reader.result);
      }, false);

      reader.onerror = () => {
        return reject(this);
      };
      reader.readAsDataURL(imageData);
    })

    return resultData
  };

After defining the function, proceed to call it in the following manner

imageSourceString = await this.convertToDataURL(imageSource)

Answer №3

Incorporating Angluar's HttpClient and a Service is essential for efficient implementation in Angular.

To utilize HttpClient effectively, we must first include the HttpClientModule within the relevant Module of our project.

@NgModule({
  imports: [HttpClientModule],
  ...
})
export class AppModule {}

Subsequently, establishing a generic Image Service that accesses HttpClient through dependency injection is crucial.

@Injectable()
export class ImageService {
  constructor(private http: HttpClient) { }
}

Once these steps are completed, we can proceed to create the function in our service:

imageUrlToBase64(url: string) {
  return this.http.get(url, {
      observe: 'body',
      responseType: 'arraybuffer',
    })
    .pipe(
      take(1),
      map((arrayBuffer) =>
        btoa(
          Array.from(new Uint8Array(arrayBuffer))
          .map((b) => String.fromCharCode(b))
          .join('')
        )
      ),
    )
}

By using http.get with an arraybuffer response type, we receive the image data as an ArrayBuffer, enabling us to convert it into a base64 string easily. Alternative methods can be explored on this helpful SO Question.

// code snippet from above
map(
  btoa(
    Array.from(new Uint8Array(arrayBuffer))
    .map((b) => String.fromCharCode(b))
    .join('')
  )
)

With the function now implemented, we can move on to utilization:

@Component()
export class AppComponent {
  base64Image: string;
  constructor(private imageService: ImageService) {
      this.imageService.imageUrlToBase64('https://picsum.photos/200/300').subscribe(
          base64 => {
              this.base64Image = base64
      })
  }
}

At this stage, the image is accessible in base64 format.

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

Can the pointerover event be managed on a container within the am5 library?

While attempting to add an HTML label to a map and trigger a pointerover event, I encountered issues. The objective was to change the HTML content upon hover. Despite trying to incorporate a tooltip, the hover event failed to work properly, and the tooltip ...

What methods are most effective for verifying user credentials in a web application using Node.js and AngularJS?

Currently, I am working on a project that involves using Node.js and MySQL for handling user data. I would like to leverage the user information stored in the MySQL database, but I am unsure about the most secure method for implementing user authentication ...

Angular: Incorporating a custom validation function into the controller - Techniques for accessing the 'this' keyword

I'm currently working on implementing a custom validator for a form in Angular. I've encountered an issue where I am unable to access the controller's this within the validator function. This is the validator function that's causing tr ...

What steps should be taken to showcase user input in a newly created task?

I am struggling to display the user input list, but it seems like I might be missing something here: const createTask = () => { const id = createId() const task = elements.input.value; const date = elements.cal.value; if(!task && ...

The specified property cannot be found within the type 'JSX.IntrinsicElements'. TS2339

Out of the blue, my TypeScript is throwing an error every time I attempt to use header tags in my TSX files. The error message reads: Property 'h1' does not exist on type 'JSX.IntrinsicElements'. TS2339 It seems to accept all other ta ...

The deletion request using the form in Express is experiencing issues and not functioning properly

When attempting to delete data from a database using a form in node.js and express, I am encountering issues with the deletion process. It seems that there are only two methods available - get and post - and no specific delete method. router.js code rout ...

Executing a function with the initial click

Is there a way to run a function only on the first click, without having it run every time? I already have another function running on window.onload, so I can't use that. Both functions work fine independently, but not together. Right now, I'm ca ...

What is the method to restrict the selection of only one option for specific values in a multiple-selection dropdown menu?

Is there a way to create a dropdown menu with the following functionalities: I want to allow multiple selections for options A, B, and C, but disable multiple selection if option D is selected. Any tips on how to achieve this? Thank you. <label>Ch ...

Using $.getJSON is not functioning properly, but including the JSON object directly within the script is effective

I'm currently working on dynamically creating a simple select element where an object's property serves as the option, based on specific constraints. Everything is functioning properly when my JSON data is part of the script. FIDDLE The follow ...

Performing an Angular 5 JSONP request using custom HttpHeaders

I'm attempting to make a JSONP request with specific HTTP header parameters. Using http.get makes it simple: let header = new HttpHeaders(); header.append(<header_param_name>, <header_param_value>); this.http.get(<my_url>, { header ...

Troubleshoot React component re-rendering issue

I'm currently facing a challenging bug that only occurs very sporadically (about once every few dozen attempts). During the render call, I'm determined to gather as much information as possible: I want to understand what triggered the rerender ...

What is the best way to retrieve an object from the state in my React application?

I have been struggling to locate an item from a collection so that I can update my react component. Despite the fact that the propertyState object is not empty and contains a list that I have successfully console logged, I keep receiving an undefined obj ...

Navigating to the HomePage using the nebular auth/login library with the login() function: A step-by-step guide

After setting up my Angular Project and installing the nebular library, I am working on creating 3 pages: Login, Register, and Home. I have successfully created the login and register pages using NbLoginComponent and NbRegisterComponent. Now, my goal is to ...

The name 'withStyles' is nowhere to be found

import * as React from "react"; import Button from "@material-ui/core/Button"; import * as PropTypes from "prop-types"; import {WithStyles} from '@material-ui/core'; import "./App.css"; import PageTwo from "./components/PageTwo"; ...

Transform a list separated by commas into an unordered list

Seeking a PHP, Jquery, or JavaScript method to convert comma-separated data into an unordered list. For clarification, I have uploaded a CSV file to WordPress where one section of content is separated by commas and I am looking to display it as a list. A ...

A method for categorizing every tier of JSON data based on a shared attribute

I am encountering issues with my project as I attempt to construct a tree using JSON data. Here is an example of what I have: var treeData = [ { "name": "Root Node", "parent": "null", "children": [ ...

Communication between a local server and the browser rendering in Angular

It seems like I may be approaching this task in the wrong way. Currently, I have a Nodejs server running that reads data from a DB and serves it locally through express using http. The server sends the data on localhost at a specific port (for example, 80 ...

Allowing multiple requests to be executed simultaneously in Express.js without causing any blocking issues

I am facing an issue with my Express.js website while handling post requests. The server hangs when a request triggers a query that takes several minutes to execute and respond from the database. Below is the code structure I use for database queries: Se ...

Issues with the functionality of AngularJS router implementation

I have searched through various resources like Stack Overflow and other blogs, but unfortunately, I haven't been able to fix the routing issue in my AngularJS code. Although there are no error messages, the routing functionality doesn't seem to b ...

What is causing the Angular HTTP Post method error "Property 'post' is undefined"?

Encountering an error while using Angular's HTTP Post method: Cannot read property 'post' of undefined. I am attempting to send my first HTTP POST request, but it is not functioning as expected. export class RegisterComponent impleme ...