如何解码base64 SVG文件并将其用作Angular模板?

问题描述

我想将base64编码的SVG图像转换为扩展名为.svg的Angular模板,例如my-template.component.svg。

我通过API调用以以下形式获取base64编码的svg:

data:image/svg+xml;base64,PHN2ZyBpZD0iREVWSUNFX01BUF8tX09wZW5lZF9jb3B5IiBkYXRhLW5...

这应该成为普通的SVG文件,我想将其用作模板。因此my-template.component.svg内容应如下所示:

<svg width = "100" height = "100">
   <circle cx = "50" cy = "50" r = "40" stroke = "green" stroke-width = "4" fill = "yellow" />
   ...
</svg>

否则,由于选择器在DOM中不可用,因此我无法使用CSS处理base64编码的SVG。

当前,从API调用返回的值的用法如下:

<img id ="img" [src]="api-url +'/path/to/svg/file.svg'" />

因此img标签的src属性变为:

<img id="img" src="data:image/svg+xml;base64,PHN2ZyBpZD0iREVWSUNFX01BUF8tX09wZW5lZF9jb3B5IiBkYXRhLW5..." />

解决方法

您的API返回base64编码的数据URL。 您可以将编码后的部分(在“ data:image / svg + xml; base64”之后)并在base64编码器/解码器中使用:

https://www.base64decode.org/

获得的SVG XML can be used in Angular模板(8个以上的CLI)