angular2显示base64图像

时间:2016-11-07 16:47:33

标签: image angular base64

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

服务:

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;
        });
    }
}

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

我会很感激这个简单问题的一个有效例子。

1 个答案:

答案 0 :(得分:11)

以下示例显示如何使用ASP.NET Core和Angular 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;
}

PhotoService (Angular服务)

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

<强>实体component.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">