What is the process for converting an image into base 64 using Angular 5?

Is there a way to convert an image into base 64 using angular5 when the image is sourced from Facebook or Google authentication API?

I seem to be encountering an issue, what could I be doing wrong?


getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.src.width;
canvas.height = img.src.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}

// Usage


var url=" https://www.livemint.com/rf/Image-621x414/LiveMint/Period2/2017/06/12/Photos/Opinion/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2d594841484e42400046401500001b1f1c55191c196d61445b486044435903677d6a">[email protected]</a>";

var base64 = this.getBase64Image(url);

//error


ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'width' of undefined TypeError: Cannot read property 'width' of undefined

Answer №1

Converting an Image to base64 is a simple process if you have the image stored as a File. One way to achieve this is by using a FileReader in JavaScript:

convertToBase64(file: File): string {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => {
        const base64String = (reader.result as string).match(
            /.+;base64,(.+)/
        )[1];
        return base64String;
    };
}

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

Why do selected items in Ionic 3 ion-option not get deselected even after reloading or reinitializing the array

HTML File: <ion-item class="inputpsection" *ngIf="showDeptsec"> <ion-label floating class="fontsize12">Department</ion-label> <ion-select (ionChange)="showDepartmentChosen($event)" multiple="true" formControlName=" ...

The Conundrum of Angular 5 Circular Dependencies

I've been working on a project that involves circular dependencies between its models. After reading through this StackOverflow post and its suggested solutions, I realized that my scenario might not fit into the category of mixed concerns often assoc ...

Troubleshooting Issue: Angular 6 - Authentication token interceptor not including headers

After experimenting with various approaches using Angular 6 for the past couple of days, I recently tried implementing a solution mentioned in this post: . Despite my efforts, the header in the requests still remains unset. import {Inject, Injectable} fro ...

Zod vow denial: ZodError consistently delivers an empty array

My goal is to validate data received from the backend following a specific TypeScript structure. export interface Booking { locationId: string; bookingId: number; spotId: string; from: string; to: string; status: "pending" | "con ...

Using a Component as a Property in Angular

There is a small gridComponent: @Component({ selector: 'moving-grid', templateUrl: './grid.component.html', styleUrls: ['./grid.component.css'] }) export class GridComponent { @Input('widgets') ext ...

Measuring Feedback: Utilizing Angular 4 to calculate review ratings

I'm facing a challenge while working on a review form using Firebase and Angular 4. The issue is with calculating the total length of added reviews and the sum of their ratings. Each time a new review is submitted, it gets pushed to a list of objects ...

Is it better to convert fields extracted from a JSON string to Date objects or moment.js instances when using Angular and moment.js together?

When working on editing a user profile, the API call returns the following data structure: export class User { username: string; email: string; creationTime: Date; birthDate: Date; } For validating and manipulating the birthDate val ...

Evaluation of button display based on certain conditions

I currently have two different render functions that display certain elements based on specific conditions. The first render function looks like this: private render(): JSX.Element { return ( <div> {this.props.x && this.state.y ...

Having trouble accessing specific results using Firestore's multiple orderBy (composite index) feature

I am facing an issue with a query that I run on various data types. Recently, one of the collections stopped returning results after I included orderBy clauses. getEntitiesOfType(entityType: EntityType): Observable<StructuralEntity[]> { const col ...

What is the best way to export a ReactTS component along with its children?

After importing the component, I proceed to declare a new component which will be a child for the invoked one. import { someComponent } from './someComponent'; This is how I export it: const anotherComponent = () => {...}; export { someCompon ...

The TypeScript Promise error codes TS2304 and TS2529 are causing confusion among

I came across the code below: function asyncTask(): Promise<string> { return new Promise<string>(resolve => resolve); } This code resulted in the following error: TS2304: cannot find name 'Promise' To address this issue, ...

Setting the default selected row to the first row in ag-Grid (Angular)

Is there a way to automatically select the first row in ag-grid when using it with Angular? If you're curious, here's some code that may help: https://stackblitz.com/edit/ag-grid-angular-hello-world-xabqct?file=src/app/app.component.ts I'm ...

Disabling an anchor using the 'disabled' property is proving to be a challenge for me

I'm attempting to dynamically enable or disable an anchor element based on the user's role. So far, I've tried a few different methods: document.getElementById('myBtn').disabled = true; However, this returns an error: The propert ...

tips for resolving pm2 issue in cluster mode when using ts-node

I'm having an issue using pm2 with ts-node for deployment. Whenever I try to use cluster-mode, a pm2 instance error occurs, saying "Cannot find module..." Error: Cannot find module '{path}/start' at main ({path}/node_modules/ts-node/dist/b ...

The access to the HTTP response object is not possible: the property is not found on the Object type

I recently created a response object and assigned it to the "this" object. However, when I try to access the datacentersinfo property, I encounter an error stating that the property does not exist on type Object. Due to this issue, I am unable to generat ...

Create an array filled with multiple arrays containing objects

To achieve the desired array of array of objects structure, I need to populate the data like this: let dataObj = [ [ { content: "test1"}, { content: "test2"}, { content: "test3"} ], [ ...

Is it possible to display a modal view when clicking on a textfield without the keyboard automatically popping up?

As a beginner in the realm of AngularJS and the Ionic framework, I am currently working on developing a hybrid app utilizing PhoneGap and Ionic. I have encountered a scenario where, upon clicking a UITextField, a modal should appear with a list of account ...

Issue TS2315: Type 'ElementRef' does not support generics

While attempting to integrate @angular/materials into my application, I encountered a successful compilation with the following error messages: webpack: Compiled successfully. ERROR in node_modules/@angular/material/button-toggle/typings/button-toggle.d.t ...

Setting up AngularJS 1.5.x to function seamlessly with SystemJS and TypeScript

I'm looking to keep all my code in AngularJS 1.x while also preparing it for an easy upgrade to AngularJS 2 in the future. To align my code with Angular 2 standards, I am interested in using TypeScript and SystemJS in version 1.5.x initially. Is ther ...

Facing unexpected behavior with rxjs merge in angular5

import { Observable } from 'rxjs/Observable'; import 'rxjs/add/observable/merge'; this.data = this.itemsCollection.valueChanges() this.foo = this.afs.collection<Item>('products') .doc('G2loKLqNQJUQIsDmzSNahlopOyk ...