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

Struggling to translate JavaScript code into Typescript

Currently in the process of converting my JavaScript code to Typescript, and encountering an error while working on the routes page stating Binding element 'allowedRoles' implicitly has an 'any' type. ProtectedRoutes.tsx const Protecte ...

Exploring the Features of Angular 6 through Interface Properties

Is there a way to add a description attribute to a property, similar to the data descriptions in dot net? For example: interface ModuleStatus { [Description "Module state"] moduleStateSymbol: string; [Description "Module type"] moduleTypeS ...

Definition of TypeScript for caching middleware in Express

I recently came across a helpful Medium post that inspired me to create an express middleware function for caching the response. However, I'm facing some challenges while trying to implement it in typescript. Specifically, I am struggling to identify ...

The next button will only activate once all input forms have been completed in multiple forms

In the JavaScript code: var current_fs, next_fs, previous_fs; //fieldsets var left, opacity, scale; //fieldset properties that will be animated var animating; //flag to prevent rapid glitches from multi-clicking $(".next").click(function(){ if(animati ...

Issue with material datepicker not initializing start value when input field is clicked

Using the Material date picker, I've implemented the date picker feature with the startAt binding to establish a default selected value. Users can open the calendar overlay by clicking on the input field, thanks to the (click) and (focus) event bindin ...

How can you customize the appearance of the filledInput component within a TextField component in Material UI?

I need some guidance on how to change the color of the FilledInput component within a TextField. Unlike InputProps, FilledInputProps are not directly accessible for styling with classes. Any suggestions on how I can customize the styling of the FilledInpu ...

Express is having trouble rendering the static index file

I am currently working on an Angular application, where my goal is to serve the build files from the Angular application using the dist directory in my express server. In order to achieve this, I am copying the files generated by ng build and pasting them ...

A timer created using jQuery and JavaScript

Looking for a way to automatically transition between three div elements with a fade in/out effect every 8 seconds? Check out this simple code snippet I wrote: $(".link1").click(function () { $(".feature1").fadeIn(1000); $(".feature2").fadeOut(1000) ...

How to pass only the clicked element to the onClick function in React.js

I have several elements with the same className, and I want to add the className active to an element (with the className history-node) when it is clicked, in addition to its current className. However, I am facing an issue where the child elements of tha ...

Best method for distributing components across nextjs zones?

Scenario: I am currently working on a project using Next.js and taking advantage of its multi zones feature. This feature allows us to run multiple independent NextJS applications as a unified app, managed by different teams. The Issue: One challenge I fa ...

Using Angular 2, NodeJS, and Mongoose to send data from an Angular 2 frontend to a NodeJS backend REST API. However, encountering an issue where the Node API logs show that the OPTIONS

I am facing an issue with sending data from my Angular2 frontend API to the backend client, which is built using NodeJS and mongoose. When I inspect the data being sent on the Angular2 client through console.log, I can see that the correct values are being ...

A guide on navigating through nested JSON objects with the help of async.js

Having recently transitioned from a Python background to nodeJS/Javascript's asynchronous nature, I am exploring how to traverse a nested JSON object and extract its values using async.js. In my quest for answers, I stumbled upon this helpful snippet ...

Tips on editing a file exclusively when a specific requirement is fulfilled

Looking for a way to implement a put method within an Express API that allows users to update a document conditionally? Consider this scenario: you have an Instance document with an attribute called executed, which is set to true if the instance has been e ...

Get the game using electron / determine the game's version via electron

I'm currently working on creating a game launcher using electron. There are two main questions that I have: What is the best method for downloading files from the client (specifically in AngularJS)? FTP or HTTP? How can I implement a system to detect ...

Exploring Custom Validator Comparisons in Angular

Having trouble comparing two input values in a custom validator. An error should occur if the minValue exceeds the maxValue. FormGroup: sumFormGroup = this.formBuilder.group({ from: ['', [Validators.min(0), sumValidator]], to: [&ap ...

jQuery.ajax Failure Response

When using MVC on the server side and calling a function with jQuery.Ajax that returns JSON, an exception is being thrown. How can I invoke the error handling function of Ajax by sending something back in the return JSON function? MVC Function public Jso ...

Attempting to send a POST request, only to be informed by the form that it is devoid of

I have been struggling with this problem for some time now. I implemented the category_create_post functionality in the categoryController, and everything seems to be set up correctly. I also configured the category_form.ejs to accept user input. However, ...

Using Angular to access HTML content through the .ts file

Is there a way to retrieve the value of the input field [newUser] when clicking on the button and executing the action [onAddUser()] in the .ts file? <input type="text" ng-model="newUser" style="text-align:center"/> <button (cl ...

JQuery Ajax request produces the message "Insufficient storage to fulfill this operation."

Encountering an error while attempting to pass the result.target of an OnLoad event in FileReader.readAsArrayBuffer call using a jQuery Ajax POST. The POST is not being executed, and this issue seems to be specific to IE, as it functions correctly in Chrom ...

The function `jQuery .html('<img>')` is not functional in Firefox and Opera browsers

This particular code snippet jq("#description" + tourId).html('<b>Opis: </b> '+ data); has been tested and functions correctly in Internet Explorer, Firefox, and Opera. However, when it comes to this specific piece of code jq("#i ...