image - angular2显示base64图片

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

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

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

最佳答案

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

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

entity-component.html

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

关于image - angular2显示base64图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40470288/

相关文章:

html - 如何让三个div水平排列

python - 在Python中重新排列图像

Android - 显示来自可绘制资源的图像

java - Android:如何检查字符串是否为 Base64 编码?

c# - 如何从 Webapi 将 URL 传递到 <img> 标记以接受 base64 图像?

ios - 使用 UIGraphicsImageRenderer 绘制图像时为什么要使用大量内存?

angular - 如何获得 ng-content 选择过滤器来处理投影模板内容?

angular - 缩短 Azure Devops 中 Angular 8 应用程序的生产构建时间

Angular 9 - Istanbul 尔测试覆盖率报告生成为空

c++ - C++ 模幂运算的问题