【问题标题】:angular2 display base64 imageangular2显示base64图像
【发布时间】:2016-11-07 16:47:32
【问题描述】:

我正在尝试将来自服务器的图像显示为 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;
        });
    }
}

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

我会感谢这个简单问题的工作示例。

【问题讨论】:

  • 如果您使用方括号绑定,那么您将绑定到一个对象并需要像这样重写它:[src]="'data:image/PNG;base64,' + imageContent",但这将被 Angular 2 删除 - 请参阅这篇文章:@987654321 @.

标签: image angular base64


【解决方案1】:

以下示例展示了如何使用 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());
}

实体组件.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;
        }
    });

entity-component.html

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

【讨论】:

  • 如何实现延迟加载以加载 base64 图像?
猜你喜欢
  • 1970-01-01
  • 2021-12-20
  • 2017-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-15
  • 2019-06-25
  • 2013-01-31
相关资源
最近更新 更多