簡體   English   中英

如何以角度將base64字符串插入圖像src

[英]how to insert base64 string to image src in angular

在我的 config.ts 中,

export const imageBase64 = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAiAAA...." 

在我的 conmonent.ts


import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
import { imageBase64 } from './config'
...
  myImg: SafeUrl; 
  constructor(private sanitizer: DomSanitizer){
     this.myImg= this.sanitizer.bypassSecurityTrustUrl(imageBase64 );
  }

在我的 html 中

<img [src]="myImg" alt="" />

不幸的是,這失敗了,錯誤消息net::ERR_INVALID_URL

然后我使用bypassSecurityTrustResourceUrl失敗了,這有什么問題?

我們不需要清理 base64 數據。 我們可以使用字符串插值來以字符串的形式顯示我們擁有的任何數據

<img src={{ imageBase64}} alt="" />

您可以使用插值: src={{myImg}}

請參閱下面的 jsFiddle 以提供幫助: https ://jsfiddle.net/Lt7aP/4/

使用get屬性返回 url

public get myImg(): string {
  return this.sanitizer.bypassSecurityTrustUrl(imageBase64 );
}

工作正常。 嘗試演示並找出您出錯的地方。

<img [src]="imageBase64" alt="">

演示: https : //stackblitz.com/edit/angular-rzjusl

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM