Converting base64 dataUrls into images using typescript

When using ng2-image cropper, it does not accept the "src" attribute and instead requires the "image" attribute.

As a result, if a dataUrl is provided, the image will not display in the cropper.

I am utilizing the camera to capture an image and obtaining a base64 image from it.

I need to convert the base64 dataUrl to an image so that it can be used in the following code:

//component.html 

<div *ngSwitchCase="'camera'">
        <mat-dialog-actions>
            <button mat-raised-button class="capture" (click)="capture()">Take Photo</button>
            <button mat-raised-button mat-dialog-close class="cancel" (click)="closeCamera()" (click)="openDialog()">Cancel</button>
        </mat-dialog-actions>
        <canvas #canvas id="canvas" width="400" height="400"></canvas>
    </div>
    <img-cropper #cropper [image]="data" [settings]="cropperSettings"></img-cropper>


    <span class="result rounded" *ngIf="data">


    <img src="{{data}}" [width]="cropperSettings.croppedWidth"       
      [height]="cropperSettings.croppedHeight"> 

    </span>

The process involves capturing an image from the camera, drawing it on a canvas, and then converting it to a dataUrl.

   // component.ts
    public async capture() {
    var context = this.canvas.nativeElement.getContext("2d").drawImage(this.video.nativeElement, 0, 0, 400, 400);
    await this.captures.push(this.canvas.nativeElement.toDataURL("image/png"));
    this.state = 'photo';
    this.data = this.canvas.nativeElement.toDataURL("image/png");
    localStorage.setItem('webcam', this.data);
}

Answer №1

Below are the steps you can take...

Start by transforming the data URL into a blob:

convertDataUrlToBlob(dataUrl): Blob {
    const arr = dataUrl.split(',');
    const mime = arr[0].match(/:(.*?);/)[1];
    const bstr = atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);

    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }

    return new Blob([u8arr], {type: mime});
}

Then, utilize the blob to generate an object URL:

const objectURL = URL.createObjectURL(convertDataUrlToBlob(dataUrl));

To finalize, set the object URL as the src for your image:

document.getElementById('myImage').src = objectURL;

If preferred, you can also change the Blob into a File:

const file = new File([convertDataUrlToBlob(dataUrl)], filename, {type: `image/${extension}`});

Answer №2

<custom-image-cropper [imageURL]="dynamicFileUrl">
</custom-image-cropper>

The imageURL attribute can be set to any variable like "dynamicFileUrl" in the TypeScript file.

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

Assigning a value to an angular object

In my current project with Angular 16, I am executing a query on the database and assigning the returned number to a document number. Data Model export class Document { doc_data: string =""; doc_for: string=""; doc_number: number = 0; doc_ ...

Dealing with custom path problems in Angular 2+ webpack configurations

I am interested in using the @ngneat/tailwind schematics to convert an Angular project into one with a custom webpack configuration. However, after adding this, my scss import paths for fonts and other partial scss files are not resolving, resulting in th ...

The promise catch method does not handle JSON parsing correctly

Utilizing Angular's Http to interact with my API has been successful for handling responses with a status of 200. The data is parsed correctly and outputted as expected within the first .then() block. However, when encountering an error with a status ...

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 ...

Error in TypeScript when using keyof instead of literal in type pattern.Beware of TypeScript error when not

let c = { [X in keyof { "foo" }]: { foo: "bar" } extends { X } ? true : false }["foo"]; let d = { foo: "bar" } extends { "foo" } ? true : false; c and d should both return true, but surprisingly, c is eval ...

What could be causing the error in Angular 2 when using multiple conditions with ng-if?

My aim is to validate if the length of events is 0 and the length of the term is greater than 2 using the code below: <li class="more-result" *ngIf="events?.length == 0 && term.value.length > 2"> <span class="tab-content- ...

What is the best way to set up the typeRoots option for proper configuration

I have a unique yarn monorepo structure that is oddly shaped. Here's how it's set up: monorepo root ├── frontend │ ├── dashboard <-- not managed by yarn workspaces │ | ├── src │ | ├── node_modules │ ...

efficiently managing errors in a Nest Jest microservice with RabbitMQ

https://i.sstatic.net/sUGm1.png There seems to be an issue with this microservice, If I throw an exception in the users Service, it should be returned back to the gateway and then to the client However, this is not happening! The client only sees the de ...

What could be the reason for mocha failing to function properly in a project that is set up

During a unit test in my TypeScript project using mocha, I encountered an issue when setting the project type to module. The error message displayed is as follows: ➜ typescript-project yarn test yarn run v1.22.17 warning package.json: No license field $ ...

Issues with Injectable Service within Another Service in Angular 2

Having a problem with injecting a service into another service. I have a ContactService that retrieves data from the server using the handleError method, and an AlertService that handles errors thrown from the handleError method. Both services are declared ...

The saved editable input number is automatically pushed even without needing to click on save or cancel

I am working with a datatable, chart, and a label that shows the latest added value. The table and chart display time-series data for the last 30 minutes, including the timestamp and a random numerical value between 0 and 999. Every 10 seconds, a new data ...

I'm encountering an issue with my Next.js development server at localhost:3001 where all routes are displaying a 404 not found page. What

Currently working on a Next.js dashboard app and encountering an issue where my localhost keeps redirecting me to the 404 page. This has happened before, but I can't recall how I resolved it. Here is the recurring problem: I attempted deleting the .n ...

Insert a fresh element above the existing elements fetched from the API

My application consists of two components: add-product.component and show-list.component. The show-list component displays a list obtained from the list-product API, which requires 3 parameters in the body (user_id, session_key, page). The third parameter ...

Failed validation for Angular file upload

I attempted to create a file validator in the front end using Angular. The validator is quite straightforward. I added a function onFileChange(event) to the file input form to extract properties from the uploaded file. I then implemented a filter - only al ...

Using absolute imports to resolve modules in TypeScript and Next.js

When I import functions from files using absolute imports, I keep encountering errors that I have been trying to resolve. The errors manifest in a certain way, as shown here: https://i.sstatic.net/J7Ai1.png Despite the errors, the functions are successful ...

Add a React component to the information window of Google Maps

I have successfully integrated multiple markers on a Google Map. Now, I am looking to add specific content for each marker. While coding everything in strings works fine, I encountered an issue when trying to load React elements inside those strings. For ...

Customizing the design of the datepicker in Angular and then passing the formatted date to a

I need to send a date to the node for storage, but I am receiving it in this format 2022-04-26T18:30:00.000Z. I want to change it to 26-04-2022 Angular HTML Code <mat-form-field color="accent" appearance="fill"> <mat-label&g ...

Trouble with scrolling on Kendo chart while using mobile device

I am facing an issue with multiple kendo charts on my website. These charts have panning and zooming enabled, but in the mobile view, they take up 100% of the width which causes touch events to not work properly for scrolling. I attempted to attach an even ...

An error persists in PhpStorm inspection regarding the absence of AppComponent declaration in an Angular module

After creating a new Angular application, I am encountering the issue of getting the error message "X is not declared in any Angular module" on every component, including the automatically generated AppComponent. Despite having the latest version of the An ...

What steps can I take to set a strict boundary for displaying the address closer to the current location?

While the autocomplete feature works perfectly for me, I encountered an issue where it suggests directions away from my current location when I start typing. I came across another code snippet that uses plain JavaScript to solve this problem by setting bou ...