Angular 2-将Web Api中的byte []渲染为图像src [英] Angular 2 - render byte[] from Web Api as an image src

查看:66
本文介绍了Angular 2-将Web Api中的byte []渲染为图像src的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Angular 2应用程序正在连接到Web Api后端. 有一个端点返回存储在sql数据库中的图像的byte []. 如何在Angular中将其显示为图像? 我可以更改Web Api或Angular应用.

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.

我的Web Api端点看起来像这样...

My Web Api endpoint looks like this...

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

    return image;
}

我的Angular HTML看起来像这样...

And my Angular HTML looks like this...

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

我需要做哪些转换,或者api应该提供什么服务?

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

推荐答案

将映像转换为服务器上的Base64:

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" />

不要忘记将指令添加到您的directives数组中 组件.

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


使用柱塞例如用法

这篇关于Angular 2-将Web Api中的byte []渲染为图像src的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆