Acquire Base64 Representation from an HTTP Call

I'm looking for a solution to convert an image from a URL into a base64 string using two functions: getImageAsBlob and toBase64. The former uses HttpClient to fetch the image as a Blob, while the latter converts the retrieved Blob into a base64 string.

Could someone please guide me on how best to chain these functions in order to achieve this conversion with just the image URL at hand? Any help would be greatly appreciated!

Here are the functions:

toBase64(blob: Blob): Observable<string> {
        const reader = new FileReader();
        reader.readAsDataURL(blob);
        return fromEvent(reader, 'load')
          .pipe(map(() => (reader.result as string)))
    }
getImageAsBlob(url: string): Observable<Blob>{
        return this.http.get(url,{responseType:'blob'})
    }

Answer №1

If you want to generate an image, make sure to subscribe to the getImageAsBlob function and then execute your desired action when the callback is triggered. Here's an example:

    this.getImageAsBlob('url').subscribe(img => {
    this.toBase64(img);
  }, 
    err => console.log('Error', err),
    () => console.log('Completed');
);

To learn more about Subscribers, check out: https://rxjs.dev/api/index/class/Subscriber @AlexCano

Answer №2

fetchImageFromUrl("image_url")
  .pipe(
    mergeMap(responseBlob => convertToBase64(responseBlob))
  )
  .subscribe(imageData => ...)

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

Is it possible that the installation issue with 'File' from ionic-native is due to dependencies?

As a newcomer to Ionic2, I'm facing some beginner obstacles. Despite my extensive search efforts, I haven't been able to find any examples related to my issue. My current goal is to write a file to a specific directory on the device using Ionic2 ...

The ts-jest node package's spyOn method fails to match the specified overload

Currently, I'm exploring the usage of Jest alongside ts-jest for writing unit tests for a nodeJS server. My setup is quite similar to the snippet below: impl.ts export const dependency = () => {} index.ts import { dependency } from './impl.t ...

Can you achieve a union of strings and a single string?

Is there a way to create a type in TypeScript that can accept specific strings as well as any other string? type AcceptsWithString = | 'optionA' | 'optionB' | 'optionC' | string playground The goal here is to design a ty ...

Having trouble accessing child pages using the router

In my Angular 2 application, I have implemented navigation successfully with the following routes: { path: 'layer1/layer2', component: C2 } } { path: 'layer1/layer2/layer3', component: C3, canDeactivate: [CanDeactivateGuard] } }, With ...

What is the key to mastering any concept in Angular2 for optimal results?

When creating a Pipe to filter data, I often use the datatype any, allowing for flexibility with types. However, I have some questions regarding this approach: Is it considered a best practice? Does it impact performance when handling large amounts of da ...

Ensuring a User has an Image in MySQL Using Angular 6

As part of my development process, I am working on creating a new user and sending their information along with an image to a MySQL database. The process involves sending a user object with form data through the following component.ts file: subscribeUser() ...

Creating a JAR file for an Angular 2 application with Maven

My Front-End application is constructed using Angular2 + Webpack, organized as follows: > app > config > dist > dll > node_modules > src pom.xml package.json ... (other files) Currently, I am exploring th ...

"Unsubscribing in Angular via a button click: A step-by

I'm having trouble canceling a subscription for "device orientation" in Angular using (click) in HTML. I've tried multiple solutions but none seem to work. Does anyone have any ideas on how to fix this? TS // Watching the change in device compa ...

What is the function return type in a NextJS function?

In my project using NextJS 13, I've come across a layout.tsx file and found the following code snippet: export default function RootLayout({ children }: { children: React.ReactNode }) { return ( <html> <head /> <body&g ...

Leveraging Global Variables for Validation in Angular (Angular 10)

I am currently creating a form in Angular 10 which involves the use of validators. Specifically, I have been utilizing the Validators.min() method within my form... Instead of manually inputting the value '100' in the Validators.min('100&ap ...

Creating a new function within the moment.js namespace in Typescript

I am attempting to enhance the functionality of the moment.js library by adding a new function that requires a moment() call within its body. Unfortunately, I am struggling to achieve this. Using the latest version of Typescript and moment.js, I have sear ...

submitting an angular form and resetting the values afterward

I've implemented the following Angular form and I want to clear the text field after submitting the form. <form #addcheckinform="ngForm" novalidate (ngSubmit)="addcheckinform.form.valid && saveScheduleCheckin(this.che ...

What steps do I need to take to run my Angular project locally using globally installed npm packages?

I'm interested in maintaining all my packages globally, similar to how node package itself operates. For instance, if I have a package named "Highcharts" listed in my package.json file, I prefer to install it globally instead of creating a local node_ ...

Dealing with circular dependencies in NestJS by using ForwardRef

Hey everyone, I've been running into a circular dependency issue with NestJS. I tried using the forwardref method, but it hasn't resolved the problem for me. // AuthModule @Module({ imports: [ forwardRef(() => UserModule), JwtModule ...

Discovering if a dynamic ng-template within Angular is loaded

I have successfully implemented a dynamic component loader. Now, I am looking for a way to determine when it is fully loaded in order to display it only after all images are downloaded. However, I have noticed that the event binding 'loaded' doe ...

What is the method for defining a constant data type with a class property data type in typescript?

I've been working on developing a nestjs API and have been using classes to define my entities. For instance, I have created a Customer entity as shown below: export class Customer { id: number; name: string; } Now, while working on my Custom ...

Issue with Angular 4 Routing: Links are opening in new window instead of within router-outlet

I am currently facing an issue while trying to display the SuburbDataComponent HTML on the DASHBOARD-SIDE-PANEL-COMPONENT.HTML. When I click on Dashboard, it opens a new window but only displays the SuburbDataComponent.html without showing the side panel ...

Tips on reordering Angular material tabs on the fly

I am working with a group of 7 tabs using Angular material: <mat-tab-group #tabGroup [selectedIndex]="selectedIndex"> <mat-tab label="Tab 1">Content 1</mat-tab> <mat-tab label="Tab 2">Content 2</mat-tab> <mat-t ...

Show the values in the second dropdown menu according to the selection made in the first dropdown menu using Angular 8

My goal is to retrieve data and populate two dropdowns based on user selection. However, the code I've written isn't giving me the desired output and instead, errors are occurring. Being new to Angular, I would appreciate a review of my code. Her ...

Custom providers do not override Angular UrlResolver

In my Angular application, I am trying to implement a custom UrlResolver provider to incorporate cache breaking logic. I came across this question on Stack Overflow: . Unfortunately, it seems that overriding the default compiler UrlResolver using a provid ...