以下是一个使用Angular将字节数组显示为图像的解决方法的代码示例:
元素:
DomSanitizer
和HttpClient
:import { Component } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import { HttpClient } from '@angular/common/http';
DomSanitizer
和HttpClient
:constructor(private sanitizer: DomSanitizer, private http: HttpClient) { }
HttpClient
获取字节数组,并将其转换为Base64字符串:getImageData() {
this.http.get('https://example.com/api/image', { responseType: 'arraybuffer' })
.subscribe(data => {
const base64Image = btoa(String.fromCharCode.apply(null, new Uint8Array(data)));
this.imageData = this.sanitizer.bypassSecurityTrustUrl('data:image/png;base64,' + base64Image);
});
}
getImageData()
方法:ngOnInit() {
this.getImageData();
}
在这个示例中,我们使用HttpClient
发送一个GET请求来获取字节数组。然后,我们将字节数组转换为Base64字符串,并使用DomSanitizer
来信任URL,以便将其用作图像的src
属性。