Html 在图像的 src 标签中使用来自 URL 的 Base64 字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35828806/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use Base64 String from URL in src tag of image
提问by Thomas Schmidt
I have an service which returns the base64 version of an image. Now i want to use the base64 string in the src
tag of an img
. The service offers the base64 version under http://localhost:8080/file/301/base64
.
我有一个返回图像的 base64 版本的服务。现在我想使用的base64字符串中src
的一个标签img
。该服务在http://localhost:8080/file/301/base64
.
The base64 string looks like this:
base64 字符串如下所示:
data:image/gif;base64,iVBORw0KGgo ...
My img
tag on the page currently looks like this:
我img
在页面上的标签目前看起来像这样:
<img alt="" src="http://localhost:8080/file/301/base64" style="height:836px; width:592px">
Is there any way to get this running?
有没有办法让它运行?
回答by clarity123
It is not working because you are treating a page featuring a Data URL string, as if were just another type of external link-able image asset. Unfortunately linking to an external asset works for image files, but Data URLs are meant as an alternative to an external link, and thus does not work in the same way.
它不起作用,因为您正在处理具有数据 URL 字符串的页面,就好像它只是另一种类型的外部可链接图像资产。不幸的是,链接到外部资产适用于图像文件,但数据 URL 旨在替代外部链接,因此无法以相同的方式工作。
In short, to display an image making use of a data URL string, you need put the actual data URL string as the src=
value, in your case for example:
简而言之,要使用数据 URL 字符串显示图像,您需要将实际数据 URL 字符串作为src=
值,例如:
<img alt="" src="data:image/gif;base64,iVBORw0KGgo ... " style="height:836px; width:592px">
Examples
例子
Example HTML from Masinter, 1998 RFC 2397 - The "data" URL scheme:
来自 Masinter 的示例 HTML,1998 RFC 2397 - “数据” URL 方案:
<IMG SRC="data:image/gif;base64,R0lGODdhMAAwAPAAAAAAAP///ywAAAAAMAAw AAAC8IyPqcvt3wCcDkiLc7C0qwyGHhSWpjQu5yqmCYsapyuvUUlvONmOZtfzgFz ByTB10QgxOR0TqBQejhRNzOfkVJ+5YiUqrXF5Y5lKh/DeuNcP5yLWGsEbtLiOSp a/TPg7JpJHxyendzWTBfX0cxOnKPjgBzi4diinWGdkF8kjdfnycQZXZeYGejmJl ZeGl9i2icVqaNVailT6F5iJ90m6mvuTS4OK05M0vDk0Q4XUtwvKOzrcd3iq9uis F81M1OIcR7lEewwcLp7tuNNkM3uNna3F2JQFo97Vriy/Xl4/f1cf5VWzXyym7PH hhx4dbgYKAAA7" ALT="Larry">
回答by wong2
Data URIis a URI scheme, not an image file format. When you use src="http://..."
, the scheme is http
, not data
, the browser is expecting the response be an image, which means the response body should be the bytes of the image, not the base64 version.
数据 URI是一种 URI 方案,而不是一种图像文件格式。当您使用 时src="http://..."
,方案是http
,而不是data
,浏览器期望响应是图像,这意味着响应主体应该是图像的字节,而不是 base64 版本。
so you can either: 1. just return the bytes of the image from the server instead of base64 2. use ajax to load base64 version from server, then set image's src attribute with it.
所以你可以: 1. 只从服务器返回图像的字节而不是 base64 2. 使用 ajax 从服务器加载 base64 版本,然后用它设置图像的 src 属性。