Chatra
Chatra

Reputation: 3129

Return an image and display in UI using Web API core and Angular 7

I am trying to display image in UI.

Here is my ASP.NET Web API Core Code for that.

    [Route("{id:int}/image")]
    public async Task<IActionResult> GetImage(int id)
    {
        var data = await this.designService.GetImageAsync(id);

        byte[] result = data.Data;

        return this.File(result, "image/jpeg");
    }

I followed this Link I assume above code is correct(Not sure if there is a better way to return Image - please guide me)

In component, my code looks like this.

this.service.getImageThumbnail(id).subscribe(
  baseImage => {
    this.thumbnail = baseImage;
  },
  error => (this.errorMessage = error)
);

In Service, implementation is like this

getDesignThumbnail(id: number) {
return this.http
.get(`https://localhost:44314/api/designs/${id}/thumbnail`)
.pipe(catchError(error => this.errorHandler(error)));

}

In HTML, I am displaying like this.(Not sure if this is correct)

 <img width="100" height="100" data-bind="attr: { src: thumbnail }" />

I am getting this error message Error

Upvotes: 1

Views: 3461

Answers (1)

Hien Nguyen
Hien Nguyen

Reputation: 18975

You can return dynamic object in Web API and change way to show image in angular.

I used this way to display image from API.

[Route("{id:int}/image")]
    public async Task<dynamic> GetImage(int id)
    {
        var data = await this.designService.GetImageAsync(id);

        byte[] result = data.Data;

        return new { Image = result}
    }

In service add private sanitizer: DomSanitizer to constructor.

this.service.getImageThumbnail(id).subscribe(
  baseImage => {
    let objectURL = 'data:image/png;base64,' + baseImage.Image;

    this.thumbnail = this.sanitizer.bypassSecurityTrustUrl(objectURL);
  },
  error => (this.errorMessage = error)
);

Updated: I create a demo reading a jpeg image from base64 format stored json file.

Please check your image is png or jpeg in data:image/png or data:image/jpeg https://stackblitz.com/edit/display-image-from-api

Upvotes: 1

Related Questions