Angular 中未显示背景图片

background image not showing in Angular

是的,我搜索并找到了很多示例,但 none 对我有用。我不确定我做错了什么。需要帮助!

如果我输入 <img> 标签,我可以看到图像,但是当我输入 background-image 时,我看不到图像。但是当我检查元素时我可以看到二进制图像。

尝试在 stackblitz 中做一个例子 https://stackblitz.com/edit/display-image-from-rest-api-qpnspq?embed=1&file=src/app/app.component.ts

HTML:

 <!-- This works -->
 <div class="row" style="max-width: 100%; margin-left: 1px;" >
     <img id="dashboardImage" [src]='imageBlobDataUrl' height='500' width='500' />
 </div>

 <!-- This does NOT works -->
<div class="row" style="max-width: 100%; margin-left: 1px;" [style.background-image]="image"> </div>

TS:

    @Input() imageBlobDataUrl: any;
    selectedImage: QiImage = new QiImage();

    public header:SafeHtml;
    public content:SafeHtml[];
    public image:SafeStyle;

  constructor(
          private qiImageService: QiImageService,
          private sanitizer: DomSanitizer,
          private imageService: ImageService
  ) {}
  populateImageDetails(lineId, bitmapFileName) {
      this.imageService
          .populateImageDetails(lineId, bitmapFileName)
              .subscribe( (selectedImage : any) => {
                  this.selectedImage = selectedImage;
                  //let TYPED_ARRAY = new Uint8Array(selectedImage.imageData);
                  //const STRING_CHAR = String.fromCharCode.apply(null, TYPED_ARRAY);
                  //let base64String = btoa(STRING_CHAR);
                  let objectURL = 'data:image/png;base64,' + selectedImage.imageData;
                  this.imageBlobDataUrl = this.sanitizer.bypassSecurityTrustUrl(objectURL);
                  this.image = this.sanitizer.bypassSecurityTrustStyle(`url(${objectURL})`);
              });
  }

您可以将 URL 图片放在 src 上,即使它是基于 base64 的

 <img id="dashboardImage" [src]='objectURL' height='500' width='500' />

如果您尝试使用 CSS 设置背景图片?像这样:

.bg {
  background-image: url("../../yourimage");
  height: 100%;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  display: flex;
  justify-content: center;
  align-items: center;

}

在模板中,您可以根据需要使用绑定设置 css class

当我尝试你的 stackblitz 时它工作正常。您需要修复 CSS 才能在视图中显示图像。

不要将 bypassSecurityTrustUrl 用于样式 Url。所以下面的缩略图是无效的:

this.thumbnail = this.sanitizer.bypassSecurityTrustUrl(objectURL); // Do NOT Use

this.image = this.sanitizer.bypassSecurityTrustStyle(`url(${objectURL})`); // This works fine and is Valid

尝试为您的图像调整 CSS 位置,它将显示:

<div class="row" 
  style="width: 100%; height: 100%; position:absolute; 
  margin-left: 1px;  background-repeat: no-repeat;" 
  [style.background-image]="image"> </div>