Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

c# - Angular 2 - render byte[] from Web Api as an image src

I have an Angular 2 app that is connecting to a Web Api backend. There is an endpoint that returns a byte[] of an image that is stored in a sql database. How can I display this as an image in Angular? I can change either the Web Api or Angular app.

My Web Api endpoint looks like this...

[Route("api/profileimage/{userId}")]
public byte[] Get(string userId)
{
    var image = _profileImageService.GetProfileImage(userId);

    return image;
}

And my Angular HTML looks like this...

<img src="http://localhost:2116/api/ProfileImage/{{tile.UserId}}" width="100" height="100"/>

What conversion do I need to do, or what should the api serve up?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Convert the image to Base64 on your server:

[Route("api/profileimage/{userId}")]
public string Get(string userId)
{
    var image = _profileImageService.GetProfileImage(userId);

    return System.Convert.ToBase64String(image);
}

For ease of use I created a new directive to encapsulate all the code we need for getting and displaying the image:

import {Directive, OnInit, Input} from '@angular/core';
import {Http} from '@angular/http';
import {BROWSER_SANITIZATION_PROVIDERS, DomSanitizationService} from '@angular/platform-browser';

@Directive({
  selector: '[profile-image]',
  providers: [BROWSER_SANITIZATION_PROVIDERS],
  host: {
    '[src]': 'sanitizedImageData'
  }
})
export class ProfileImageDirective implements OnInit {
  imageData: any;
  sanitizedImageData: any;
  @Input('profile-image') profileId: number;

  constructor(private http: Http,
              private sanitizer: DomSanitizationService) { }

  ngOnInit() {        
    this.http.get("http://localhost:2116/api/ProfileImage/" + profileId)
      .map(image => image.text())
      .subscribe(
        data => {
          this.imageData = 'data:image/png;base64,' + data;
          this.sanitzedImageData = sanitizer.bypassSecurityTrustUrl(imageData);
        }
      );
  }
}

In your template include it like this:

<img [profile-image]="tile.UserId" width="100" height="100" />

Don' forget to add the directive to the directives array of your component.


Working Plunker for example usage


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...