I keep getting an error message from Microsoft saying the image is invalid

Whenever I attempt to send an image from a canvas to Microsoft in Typescript/Angular, I keep getting an error message:

"Decoding error, image format unsupported."

However, if I manually copy the base64 of the image into a converter, then paste it into Postman and make the request, it works perfectly fine. I have converted the base64 to a blob, so theoretically it should be sending the same image. I'm not sure where the issue lies... Could it be related to HttpClient? Here's the code snippet:

import { Component, OnInit, ViewChild } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
@Component({
  selector: 'app-generator',
  templateUrl: './generator.component.html',
  styleUrls: ['./generator.component.css']
})
export class GeneratorComponent implements OnInit {

  @ViewChild('video')
    public video;

    @ViewChild('canvas')
    public canvas;
    public urlPicture: string;
    public constructor(private httpClient: HttpClient) {
    }

    public ngOnInit() { }

    // tslint:disable-next-line:use-life-cycle-interface
    public ngAfterViewInit() {
        if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
            navigator.mediaDevices.getUserMedia({ video: true }).then(stream => {
                this.video.nativeElement.srcObject = stream;
                this.video.nativeElement.play();
            });
        }
    }

    public capture() {
        const ctx = this.canvas.nativeElement.getContext('2d');
        ctx.drawImage(this.video.nativeElement, 0, 0, this.video.nativeElement.width, this.video.nativeElement.height);
        const image = this.makeblob(this.canvas.nativeElement.toDataURL('image/png'));
        console.log(this.canvas.nativeElement.toDataURL('image/png'));
        this.detectFace(image.blob);
        this.detectSkinColor(image.blob);
    }
    private makeblob(dataURL) {
      const BASE64_MARKER = ';base64,';
      if (dataURL.indexOf(BASE64_MARKER) === -1) {
          // tslint:disable-next-line:no-shadowed-variable
          const parts = dataURL.split(',');
          // tslint:disable-next-line:no-shadowed-variable
          const contentType = parts[0].split(':')[1];
          // tslint:disable-next-line:no-shadowed-variable
          const raw = decodeURIComponent(parts[1]);
          return {
            rawlength: raw.length,
            blob: new Blob([raw], { type: contentType })
          };
      }
      const parts = dataURL.split(BASE64_MARKER);
      const contentType = parts[0].split(':')[1];
      const raw = window.atob(parts[1]);
      const rawLength = raw.length;
      const uInt8Array = new Uint8Array(rawLength);
      for (let i = 0; i < rawLength; ++i) {
          uInt8Array[i] = raw.charCodeAt(i);
      }
      return {
        rawlength: raw.length,
        blob: new Blob([raw], { type: contentType })
      };
    }
    private detectFace(blob) {
      const headers = new HttpHeaders({
        'Content-Type': 'application/octet-stream',
        'Ocp-Apim-Subscription-Key' : 'mykey'
      });
      // tslint:disable-next-line:max-line-length
      this.httpClient.post<any>('https://northeurope.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceId=true&returnFaceLandmarks=false&returnFaceAttributes=age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise', blob, {headers: headers})
      .subscribe((result) => {
        console.log(result);
      });
    }
    private detectSkinColor(blob) {
      const headers = new HttpHeaders({
        'Content-Type': 'application/octet-stream',
        'Prediction-Key' : 'mykey'
      });
      // tslint:disable-next-line:max-line-length
      this.httpClient.post<any>('https://northeurope.api.cognitive.microsoft.com/customvision/v3.0/Prediction/myprojectid/classify/iterations/Iteration1/image', blob, {headers: headers})
      .subscribe((result) => {
        console.log(result);
      });
    }
}

Answer №1

Implementing the toBlob() function has resolved all issues and now everything is running smoothly. Below is the functioning code snippet:

function takeSnapshot() {
    const context = this.canvas.nativeElement.getContext('2d');
    context.drawImage(this.video.nativeElement, 0, 0, this.video.nativeElement.width, this.video.nativeElement.height);
    this.canvas.nativeElement.toBlob((result) => {
      this.img = result;
      console.log(this.img);
      this.detectFace(this.img);
      this.detectSkinColor(this.img);

    });
}

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

Managing HTTP requests: A guide to canceling with switchMap

I need to be able to cancel a previous HTTP request if a new one is made to the server, but the current implementation is not working as expected. I want the request to be canceled if a certain value changes in the function. In other words, if the value c ...

Setting the initial state for your ngrx store application is a crucial step in ensuring the

I'm completely new to ngrx and I'm currently exploring how to handle state management with it. In my application, each staff member (agent) is associated with a group of customers. I'm struggling to define the initial state for each agent ob ...

The type 'void | Observable<User>' does not include the property 'subscribe'. Error code: ts(2339)

authenticate() { this.auth.authenticate(this.username, this.password).subscribe((_: any) => { this.router.navigateByUrl('dashboard', {replaceUrl: true}); }); } I'm puzzled by this error message, I've tried a few solu ...

What is the best way to extract values from a specific table column and store them in an array using Angular?

I have a section of code containing a table in my component: expect-next-month.component.html <table id="users"> <tr> <th>Number of month</th> <th>Total checking e ...

Is it possible to create a click event for a mat-icon within a mat form field (either in the matprefix or matsuffix)?

I am working with a mat-form-field and have incorporated a custom mat-icon within it as a matprefix. However, I am now looking to create a click method for that matprefix icon. Despite my attempts to write a click method, it does not seem to be functioning ...

Ensure that a variable adheres to the standards of a proper HTML template

I'm struggling with a problem in my Angular application. I need to ensure that a TypeScript variable is a valid HTML template to compile successfully, like this: let v = '<div>bla…</div>' However, if the variable contains inco ...

Change a TypeScript alias within the @types namespace

While using Typescript 3, I encountered a situation where I needed to modify a type alias from the @types/json-schema definition provided by DefinitelyTyped. The issue arose when I wanted to incorporate a custom schema type into my code. Since this custom ...

Issue encountered while trying to insert a new row into the mat-table

I need help with inserting a new row in mat-table using a button. I wrote a function for this, but when I click the button, I encounter an error CalculatoryBookingsComponent.html:62 ERROR Error: Cannot find control with path: 'rows -> 0'. Addi ...

Guide on extracting FormData from a POST request in Node.js using Multer

I have a specific challenge where I need to store formData on a mongodb schema, using nodejs and express for the backend, along with multer as middleware. This particular formData consists of both a string and a blob. My main issue is capturing and saving ...

Tips for avoiding the 'Duplicate keys detected' error when using a v-for loop in Vue.js

In my most recent project, I utilized Nuxt.Js along with Vuetify.js as the UI framework. The language I used was TypeScript. As part of this project, I attempted to create the image below using arrays. https://i.sstatic.net/t1Xsc.jpg export const dumm ...

Error in Typescript: The element is implicitly assigned an 'any' type due to the inability to use a 'string' type expression as an index

I'm a beginner with TypeScript and I encountered an error that's confusing to me while trying to follow an online tutorial on sorting data in Reactjs using React hooks. Here is the section of my component code where the error occurs: Element imp ...

Which is more efficient: Using TypeScript's Object.assign() or creating a new object?

Seeking advice on two different approaches to implementing a method with a constant. Unsure about the better option. Can someone provide guidance? Thank you! Approach 1: Declaring the constant outside of the class, causing it to be invoked only once but r ...

Unrestricted Angular Audio Playback without CORS Restrictions

I am currently developing a web application using Angular4 that will include the feature of playing audio files. Unfortunately, I am facing an issue where I do not have control over the server serving the media files, and therefore cannot make any modifica ...

Are additional Angular tags causing issues with the HTML layout in development mode?

When working with templates, I often find myself inserting two components inside the template of another one. Take for example this code snippet from my.component.html: // my.component.html <div class="container"> <div class="row& ...

Adding Font Awesome to my Angular 12 project within Visual Studio 2019

Seeking a no-frills guide for integrating Font Awesome (free version) into my Angular 12 application within Visual Studio 2019. After countless Google searches, I am bombarded with intricate methods. It's baffling why such complexity exists just to in ...

What causes the issue of Angular 9 routing breaking upon page refresh?

I have deployed my Angular 9 application on Heroku and everything is working perfectly. However, when I refresh the page or copy/paste a link, I get an error message saying "Cannot GET /XXX/XXX". Only the root link seems to work! Initially, I can navigate ...

Add a custom filter to the active route for a stylish look

I am trying to dynamically change the color of elements in my navbar by creating a filter in my typescript code. I have a string with values like 'greyscale(73%) saturate(1400%)'. How can I apply this string to the fa-icon's filter property ...

Issue with the <mat-chip> component in Angular Material Design

One issue I am facing is with a mat-chip list. When I close the first item it works fine, but when I close the last item, all chips are closed. https://i.sstatic.net/opj7f.png Here is the HTML code snippet: <mat-form-field> <mat-chip-list #ch ...

In what way can the result of the code displayed be considered as truthful?

this.someService.findDevices() .subscribe((segments) => { this.segments = Array.from(segments.segments); this.packs.forEach((pack) => { pack.segments = Array.from(segments.segments); pack. ...

Creating type definitions for recursive functions in TypeScript

I've created a JavaScript function that continuously accepts functions(params => string) until it receives an object, at which point it resolves the final string as a concatenation of all the functions invoked over the same object passed in at the ...