javascript 如何在Angular框架中将来自后端服务器的字节数组图像渲染为HTML DIV风格的背景图像?

ljo96ir5  于 2023-04-04  发布在  Java
关注(0)|答案(1)|浏览(67)

我尝试如下

应用程序组件.ts

import { Component } from '@angular/core';
import { ConfigService } from './config.service';
import { SettingsService } from './settings.service';
import { DomSanitizer } from '@angular/platform-browser';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  name = 'Test display image';
  imgbytData: any;
  imageBytes: Uint8Array;
  backgroundimg: any;

  constructor(private sanitizer: DomSanitizer
  ) {}

  ngOnInit() {
    this.config.getData().subscribe((baseImage: any) => {

      this.backgroundimg = this.sanitizer.bypassSecurityTrustUrl('data:image/jpeg;base64,' + baseImage.backgroundimg);
      this.imageBytes = new Uint8Array(baseImage.image);

      const base64String = btoa(String.fromCharCode(baseImage.image));
      this.sampleimg = `url(data:image/jpeg;base64,${base64String})`;
      console.log(this.sampleimg);
    });
  }
}

app.component.html

<hello name="{{ name }}"></hello>
<img id="myimage" [src]="backgroundimg" width="100px" height="70px"/>

<div  [style.background-image]="sampleimg">
  This is new DIV Tag  
</div>

config.json文件包含图片字节数组的硬编码JSON数据。

问题是<Img>标记正在渲染,但在样式标记中使用时,它不显示图像数据。

7kqas0il

7kqas0il1#

您可以使用CSS来获得正确的大小:
HTML

<hello name="{{ name }}"></hello>

<div [style.background-image]="'url(' + myImage + ')'"></div>

CSS:

p {
  font-family: Lato;
}

div {
  height: 500px;
  width: 500px;
}

TS:

import { Component } from '@angular/core';
import { ConfigService } from './config.service';
import { SettingsService } from './settings.service';
import { DomSanitizer } from '@angular/platform-browser';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  name = 'Test display image';
  myImage;

  constructor(
    private config: ConfigService,
    public setting: SettingsService,
    private sanitizer: DomSanitizer
  ) { }

  ngOnInit() {
    this.config.getData().subscribe((baseImage: any) => {
      this.myImage = 'data:image/jpeg;base64,' + baseImage.backgroundimg;
    });
  }

}

相关问题