1

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

2
  • Add the getImageThumbnail implementation Commented Mar 24, 2019 at 14:56
  • added the logic Commented Mar 24, 2019 at 15:16

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

still not displaying, Is there anything related to image size. the string looks very big when I put breakpoint at objectURL. objectURL has value but thumbnail is null

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.