Use Base64 String from URL in src tag of image

陌路散爱 提交于 2020-05-10 04:44:17

问题


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.

The base64 string looks like this:

data:image/gif;base64,iVBORw0KGgo ...

My img tag on the page currently looks like this:

<img alt="" src="http://localhost:8080/file/301/base64" style="height:836px; width:592px">

Is there any way to get this running?


回答1:


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.

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:

<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:

<IMG SRC="data:image/gif;base64,R0lGODdhMAAwAPAAAAAAAP///ywAAAAAMAAw AAAC8IyPqcvt3wCcDkiLc7C0qwyGHhSWpjQu5yqmCYsapyuvUUlvONmOZtfzgFz ByTB10QgxOR0TqBQejhRNzOfkVJ+5YiUqrXF5Y5lKh/DeuNcP5yLWGsEbtLiOSp a/TPg7JpJHxyendzWTBfX0cxOnKPjgBzi4diinWGdkF8kjdfnycQZXZeYGejmJl ZeGl9i2icVqaNVailT6F5iJ90m6mvuTS4OK05M0vDk0Q4XUtwvKOzrcd3iq9uis F81M1OIcR7lEewwcLp7tuNNkM3uNna3F2JQFo97Vriy/Xl4/f1cf5VWzXyym7PH hhx4dbgYKAAA7" ALT="Larry">



回答2:


Data URI is 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.

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.



来源:https://stackoverflow.com/questions/35828806/use-base64-string-from-url-in-src-tag-of-image

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!