angular2显示base64图像

问题描述:

我试图显示一个来自服务器的图像作为base64字符串。 http和服务器的细节对我的问题并不重要(基本上,它的工作原理)。 我有这个代码不起作用;即我看到组件中的所有数据,但屏幕上没有显示图像。angular2显示base64图像

服务:

import { Injectable } from 'angular2/core' 
import {Observable} from 'rxjs/Observable'; 
@Injectable() 
export class ImageService { 
    constructor() { 
    } 
    public getImage(): Observable<string> { 
     return Observable.create(imageData); 
    } 
} 
const imageData: string = "iVBORw0KGgoAAAANSUhE..."; 

组件:

import { Component } from 'angular2/core'; 
import { ImageService } from './service' 
@Component({ 
    selector: 'my-app', 
    template: '<div><img [src]="data:image/PNG;base64,{{imageContent}}"> </div>', 
    providers: [ImageService] 
}) 
export class AppComponent { 
private imageContent: string = ""; 
    constructor(imageService: ImageService) { 
     imageService.getImage().subscribe(response => { 
      this.imageContent = response; 
     }); 
    } 
} 

如前所述,代码不起作用。我接收到的不是屏幕上的图像:报价不支持评估!

我会欣赏这个简单问题的工作示例。

+0

如果用括号结合,然后要绑定到一个对象,并需要重写它像这样:'[SRC] =“”数据:image/PNG; base64,'+ imageContent“',但是这将被Angular 2剥离 - 请参阅此文章:http://*.com/a/38324958/1961059。 – rinukkusu

+2

[Angular 2 - 从Web Api作为图像src呈现字节\ [\]]的可能重复(http://*.com/questions/38324762/angular-2-render-byte-from-web-api-as -an图像-SRC) – rinukkusu

下面的示例示出了如何使用ASP.NET Core和角2显示base64编码图像:

PhotoController(服务器端)

[HttpGet] 
public async Task<IEnumerable<PhotoResource>> GetPhotos(int entityId) 
{ 
    // get photo information 
    // in my case only path to some server location is stored, so photos must be read from disk and base64 encoded 

    foreach (var photoR in photoResources) 
    { 
     var currPath = Path.Combine(Host.ContentRootPath, "upload", photoR.FileName); 
     byte[] bytes = System.IO.File.ReadAllBytes(currPath); 
     photoR.Content = Convert.ToBase64String(bytes); 
    } 

    return photoResources; 
} 

照片服务(角服务)

getPhotos(int entityId) { 
    return this.http.get(`${this.apiBasePath}vehicles/${vehicleId}/photos`) 
     .map(res => res.json()); 
} 

entity-componen t.ts

服务器已经发送编码的内容,所以我只准备一个包含标题和内容的属性。 Html模板是分开的。

this.photoService.getPhotos(this.entityId) 
    .subscribe(photos => { 
     this.photos = photos; 
     for (let photo of this.photos) { 
      photo.imageData = 'data:image/png;base64,' + photo.content; 
     } 
    }); 

实体component.html

<img *ngFor="let photo of photos" [src]="photo.imageData" class="img-thumbnail">