显示来自后端api的base64的不同格式的图像-angular 7

显示来自后端api的base64的不同格式的图像-angular 7,angular,image,typescript,angular7,Angular,Image,Typescript,Angular7,我有一个api,我将获得base64格式的图像,它可以是任何格式(.png、.jpg、.svg等) 我想使用以下方式在应用程序中显示图像: <img *ngIf="imageBase64" [src]="imageBase64 ? ('data:image/svg+xml ;base64,' +imageBase64 | safe) : ''" alt="" /> 以上是.svg文件的base64格式 因此,在src属性绑定中,如果我提供数据:image/svg+xml,它将起

我有一个api,我将获得base64格式的图像,它可以是任何格式(.png、.jpg、.svg等)

我想使用以下方式在应用程序中显示图像:

  <img *ngIf="imageBase64" [src]="imageBase64 ? ('data:image/svg+xml ;base64,' +imageBase64 | safe) : ''" alt="" />
以上是.svg文件的base64格式

因此,在src属性绑定中,如果我提供
数据:image/svg+xml
,它将起作用,我需要一种通用格式来打印图像,即使它是png格式等等

比如
数据:image/svg+xml/png/jpg
等等。。。不起作用的

请尝试以下操作:

<img *ngIf="imageBase64" [src]="imageBase64.base64">

试试这个:

<img *ngIf="imageBase64" [src]="imageBase64.base64">

您必须创建一个函数,该函数首先对编码字符串进行解码,然后从提供了有限类型选项集的解码字符串中提取类型

getType(imageBase64) { 
    let extension = undefined; 
    const decodedString = window.atob(imageBase64); //decode the string;
    const lowerCase = decodedString.toLowerCase();
    // find the extension in the decoded string
    if (lowerCase.indexOf("png") !== -1) extension = "png"
    else if (lowerCase.indexOf("svg") !== -1) extension = "svg+xml"
    else if (lowerCase.indexOf("jpg") !== -1 || lowerCase.indexOf("jpeg") !== -1)
        extension = "jpg"
    // add more cases if needed..
    return extension;
}
然后在模板中使用此函数

<img *ngIf="imageBase64" [src]="imageBase64 ? ('data:image/' + getType(imageBase64) + ';base64,' +imageBase64 | safe) : ''" alt="" />

您必须创建一个函数,该函数首先对编码字符串进行解码,然后从提供了有限类型选项集的解码字符串中提取类型

getType(imageBase64) { 
    let extension = undefined; 
    const decodedString = window.atob(imageBase64); //decode the string;
    const lowerCase = decodedString.toLowerCase();
    // find the extension in the decoded string
    if (lowerCase.indexOf("png") !== -1) extension = "png"
    else if (lowerCase.indexOf("svg") !== -1) extension = "svg+xml"
    else if (lowerCase.indexOf("jpg") !== -1 || lowerCase.indexOf("jpeg") !== -1)
        extension = "jpg"
    // add more cases if needed..
    return extension;
}
然后在模板中使用此函数

<img *ngIf="imageBase64" [src]="imageBase64 ? ('data:image/' + getType(imageBase64) + ';base64,' +imageBase64 | safe) : ''" alt="" />


变量的格式是什么
imageBase64
?你能举个例子吗?@callback的格式是base64,它可能包含svg或png等任何图像格式。你能举个例子吗?@callback添加了一个例子,你能看看这个例子吗?变量
imageBase64
是什么格式?你能举个例子吗?@callback是base64格式的,它可能包含任何图像格式,如svg或png等。你能举个例子吗?@callback添加了一个例子,你能看看这个吗onceThats很好,有没有其他方法可以继续,这样我们就可以从HTML而不是HTML来处理它。ts@AnilKumarReddyA,由于有必要解码和检查字符串的出现,因此不建议在模板中包含所有这些逻辑。尤其是您必须访问窗口对象,这是无法从模板访问的,除非您在.ts文件中定义它。因此,无论哪种方式,您都必须使用.ts文件。这很好,是否有其他方法可以继续,以便我们可以从HTML而不是其他方式来处理它。ts@AnilKumarReddyA,因为有必要解码和检查字符串的出现,所以不建议在模板中包含所有这些逻辑。尤其是您必须访问窗口对象,这是无法从模板访问的,除非您在.ts文件中定义它。因此,无论哪种方式,都必须使用.ts文件。