Home > Net >  How to display an image to html?
How to display an image to html?

Time:12-24

I am getting type blob image from server.

service:

  getImg(url: string, options: Object): Observable<UserI>  {
    return this._http.get<UserI>(`${environment.url}/static/${url}`, options);
  }

headers response:

HTTP/1.1 200 OK
X-Powered-By: Express
Access-Control-Allow-Origin: http://localhost:4200
Vary: Origin
Access-Control-Allow-Credentials: true
Accept-Ranges: bytes
Cache-Control: public, max-age=0
Last-Modified: Thu, 23 Dec 2021 05:41:29 GMT
Date: Thu, 23 Dec 2021 06:15:25 GMT
ETag: W/"10b2c-17de5cf037e"
Content-Type: image/webp
Content-Length: 68396

ts:

  user$!: Observable<UserI>

  ngOnInit(): void {
    ...
    const options = { responseType: 'blob'};
    this.user$ = this.userService.getImg(user.image!, options)
    ...
  }

html:

<img  *ngIf="user$ | async as user" [src]="?">

How can display the result image in html?

CodePudding user response:

<img [src]="user.image">

or

<img src="{{user.image}}">

CodePudding user response:

try to convert image response from blob to base64 and then print it in angular template

Template

<img  [src]="userImage">

Ts

ngOnInit(): void {
const options = { responseType: 'blob'};
this.userService.getImg(user.image!, options).subscribe(response=>{
const reader = new FileReader();
reader.readAsDataURL(response);
reader.onloadend = () => {
    this.userImage = reader.result; 
}
});

}

  • Related