angular - 如何使用来自 Web API 的二进制图像数据作为 DOM 元素的背景图像( Angular )

标签 angular base64 background-image asp.net-core-webapi

我在尝试获取从我的 Web API 检索的图像以在我的 Angular 应用程序中显示为背景图像时遇到了很多麻烦。

返回图像的 Web API 操作如下所示:

    /// <summary>
    /// Returns the medium image for the specified project as image/png media type.
    /// </summary>
    /// <param name="projectId"></param>
    /// <returns></returns>
    [HttpGet("{projectId:int}/image/medium")]
    [SwaggerResponse(200, typeof(byte[]))]        
    [Produces("image/png")]
    public FileContentResult GetImageMedium(int projectId)
    {            
        var res = _repository.GetProjectResource(projectId, "Medium");
        FileContentResult result = new FileContentResult(res.ByteContent, res.MediaType);            
        return result;
    }

这是目前我的 Angular 服务方法的样子(但我已经尝试了很多替代方法):

  getProjectImage(id: number) {
    return this._http
      .get(`${this._url}/${id}/Image/Medium`, { headers: this._auth.headers, responseType: ResponseContentType.Blob })
      .map(response => response.arrayBuffer());
  }

这就是我要应用于 [style.background-image] 的内容DOM 元素:

return `url(${'data:image/png;base64,' + new Buffer(response)})`

正如我之前所说,我一直在尝试将我在互联网上找到的东西组合起来,但我对所涉及的大部分内容存在固有的误解。我的 Web API 返回了什么?我该如何处理那个客户端?如何将内容整理成适合 background-image 的内容CSS属性?除了让它工作之外,我真的很想更好地理解这一点。非常感谢所有帮助!

更新

我也只是尝试更改 Web API 操作以返回如下所示的 base64 字符串:

/// <summary>
/// Returns the medium image for the specified project as image/png media type.
/// </summary>
/// <param name="projectId"></param>
/// <returns></returns>
[HttpGet("{projectId:int}/image/medium")]
[SwaggerResponse(200, typeof(byte[]))]
[Produces("image/png")]
public string GetImageMedium(int projectId)
{
    var res = _repository.GetProjectResource(projectId, "Medium");
    return Convert.ToBase64String(res);
}

并像这样在客户端处理它:

  getProjectImage(id: number) {
    return this._http
      .get(`${this._url}/${id}/Image/Medium`, { headers: this._auth.headers });
  }

并简化我的服务的调用方以向 [style.background-image] 提供以下内容DOM 元素:

return `url(${'data:image/png;base64,' + response})`

我已经 console.log编辑响应,它确实看起来像一个 base64 字符串(我认为?)。但是 css 永远不会改变。

更新2

我的标记目前是这样的:

<div class="image"
     [style.background-image]="project.image | async"></div>

我的组件的代码目前是这样的:

projects.map(project => {
  project.image = this._projectsService.getProjectImage(project.projectId)
    .map(response => `url('data:image/png;base64,${response['_body']}')`)
});

我已经到了如果我 console.log这个出来,复制它,并将其粘贴到开发工具中 div 的 css 规则中,图像显示出来。我试过在 NgZone 中运行它并且 css 仍然不会显示。感谢您提供任何帮助。

更新3

所以,如果我改变 <div class="image" [style.background-image]="project.image | async"></div><img [src]="project.image | async" alt=""> ,我让图像异步出现。这种方法的不幸之处在于,当请求正在运行时,图像错误图标是可见的。对于不返回图像(不完整的数据库)的任何项目,此错误图标仍然存在

最佳答案

为了避免在加载实际图像之前显示错误图像,请将您的 html 更改为:

<img *ngIf="project.image" [src]="project.image | async" alt="">

Update 3 中的解决方案也将有效。但是,这是另一种方法。您可以设置div 的[style] 指令来添加background-image。将样式传递给 dom 时,您必须清理样式。

In your component.html:

<div class="image" [style]="backgroundImageStyle"></div>

.. to remove the error image until we get the image, we add an *ngIf:

<div class="image" *ngIf="backgroundImageStyle" 
                    [style]="backgroundImageStyle">
</div>

... and in your component.ts:

// ..
import { DomSanitizer } from '@angular/platform-browser';

// Declare a variable to store the sanitized style
private backgroundImageStyle;

// Initialize the constructor
constructor(sanitizer: DomSanitizer) { 
    // You can call this whereever you want, I am doing it in constructor
    this.backgroundImageStyle = this.getBackgroundImageStyle();
}

private getBackgroundImageStyle() {        
    // sanitize the style expression
    style = `background-image: url(${project.image})`;
    this.sanitizer.bypassSecurityTrustStyle(style);
}
// ..

关于angular - 如何使用来自 Web API 的二进制图像数据作为 DOM 元素的背景图像( Angular ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45257766/

相关文章:

angular - 在 rxjs/Observables 范围内,变量名上的尾随美元符号是什么意思?

xml - HTTP 错误 414 - 请求的 URI 太长/base64 图像

CSS,使左右背景图像在小屏幕上滑出 View

javascript - 拉斐尔元素中的重复图案

angular - Bootstrap 在 Angular 项目中无法正常工作

angular ngx-material-timepicker 无法自定义

java - 如何使用 Base 64 调用 ocr.space API

iOS Swift base64encoding 与 PAW 应用程序 Base64 编码不同

CSS 背景图像相对背景颜色固定 z-index

angular - PrimeNG: 'p-table' 不是已知元素