Angular语言 - 从 API 渲染图像/jpeg 数据



My http call:

return http.get(url).map(res => res.text());

元件:

httpService.getCustomBanner('path').subscribe(
data => {
this.image = 'data:image/jpeg;base64,'+ data
})

.HTML:

<div *ngIf = "image">
<img [src]="sanitizer.bypassSecurityTrustUrl(image)"/>
</div>

我没有收到任何错误,并且 API 返回一种类型的图像/jpeg, 但没有什么是渲染。

编辑:取出data:image/jpeg;base64以及dee zg的答案是修复它的原因。

在你的 http 调用中,你需要这样的东西(未经测试,从头写(:

.map(res => res.blob())
.map(blob => URL.createObjectURL(blob))

这将返回一个DomString,您可以将其输入到IMG源中。

谢谢。我尝试了很多帖子,但这个对我有用。对于其他人,我将在这里发布我的经验。对于我的测试,我的 asp.net 核心 API 返回一个带有 byte[] 数据类型图像的学生列表,该图像映射到 Angular 中的 Blob。 此外,在 Angular 中,类中的字段名称必须以小写字母开头以供引用,无论其声明如何。例如。

Student.Photo; // is declared in a Student class. 
students: Student[];
//Call an api and put the result into students. 
students[0].photo worked. But students[0].Photo caused an error of 'undefined'.

有关多个图像的工作示例,请参阅以下代码。

--角度组件 HTML -----

<tr *ngFor="let item of studentList">
<td>{{item?.given1}}   --  {{item?.surname}}</td>
<td>          
<img [src]="getImangeUrl(item?.photo)"/>
</td>        
</tr>

-- 在组件 .ts 文件中

public getImangeUrl(photo:Blob): any {    
if (photo === null)
return "";
else
{
let objectURL = 'data:image/jpeg;base64,' + photo;
return this.sanitizer.bypassSecurityTrustUrl(objectURL);   
}
}

最后它对我有用。大多数示例仅适用于单个图像,如上例所示,这很容易做到。祝您编码愉快!

尝试使用以下方法

在组件中定义一个函数

import {DomSanitizer} from '@angular/platform-browser';
...
constructor(private sanitizer:DomSanitizer){}
sanity(url)
{
return this.sanitizer.bypassSecurityTrustUrl(url)
}

并在模板中使用

<div *ngIf = "image">
<img [src]="sanity(image)"/>
</div>

嗨,我不确定 [src],但您可以使用以下代码并测试它是否适合您

<div *ngIf = "image">
<img src="{{sanitizer.bypassSecurityTrustUrl(image)}}"/>
</div>

最新更新