如何正确编码 img src data:image/svg+xml 的内容? [英] How to properly encode content of img src data:image/svg+xml?
问题描述
假设我们有一个像这样的简单 SVG:
Let's say we have a simple SVG like this:
<svg xmlns="http://www.w3.org/2000/svg" width="120" height="25">
<rect x="0" y="0" width="120" height="25" stroke-wdith="1px" stroke="#000000" fill="#ffffff"/>
<text x="60" y="15" stroke-width="0pt" font-family="arial,helvetica,sans-serif" font-size="11px" font-weight="normal" font-style="normal" text-decoration="none" display="inherit" text-anchor="middle">
Some text & Other text
</text>
</svg>
注意&"字符和nbsp"HTML 实体.
Notice the '&' caracters and the "nbsp" HTML entity.
这会产生这个图像:
现在,如果我使用 encodeURIComponent 为我的图像获取正确的数据,我会得到:
Now if I use encodeURIComponent to get the proper data for my image, I get this:
%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22120%22%20height%3D%2225%22%3E%3Crect%20x%3D%220%22%20y%3D%220%22%20width%3D%22120%22%20height%3D%2225%22%20stroke-wdith%3D%221px%22%20stroke%3D%22%23000000%22%20fill%3D%22%23ffffff%22%2F%3E%3Ctext%20x%3D%2260%22%20y%3D%2215%22%20stroke-width%3D%220pt%22%20font-family%3D%22arial%2Chelvetica%2Csans-serif%22%20font-size%3D%2211px%22%20font-weight%3D%22normal%22%20font-style%3D%22normal%22%20text-decoration%3D%22none%22%20display%3D%22inherit%22%20text-anchor%3D%22middle%22%3ESome%20text%20%26%20Other%26nbsp%3Btext%3C%2Ftext%3E%3C%2Fsvg%3E
在 HTML 图像中使用它 <img src="data:image/svg+xml,...,/>图片无法加载.
Using this in an HTML image the <img src="data:image/svg+xml,...,/> the image won't load.
修复"nbsp"部分,我可以使用像 he 这样的库来解码 HTML.如果我删除&"它有效.
To fix the "nbsp" part, I can use a library like he to decode the HTML. If I remove the '&' it works.
但是&",即使我看到它被 %26 编码,也会阻止图像加载.
But the '&', even if I see it gets encoded with %26, prevents the image from loading.
我不知道是否还有其他类似的字符会阻止图像加载,所以我想知道我应该如何处理文本(可以是任何内容)以确保它始终正确呈现.
I don't know if there's other caracters like this that would prevent the image from loading so I'm wondering how I should deal with the text (which can be anything) to be sure it is always rendered properly.
推荐答案
它不是有效的 XML.您应该首先将 &
替换为 &
.只有 5 个 XML 实体(<
、>
、&
、"
, '
).其他 HTML 实体根本不是 SVG 的一部分.您可以将
替换为 unicode \u00A0
或  
或真正的 unicode 字符 "".
It is not valid XML. You should replace &
with &
in first place. There are only 5 XML entities (<
, >
, &
, "
, '
). Other HTML entities is not part of SVG at all. You can replace
with unicode \u00A0
or  
or real unicode character " ".
最终的
Final <text>
content can be one of
Some text & Other\u00A0text
Some text & Other text
Some text & Other text
这篇关于如何正确编码 img src data:image/svg+xml 的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!