Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Base64 String from URL in src tag of image

Tags:

html

image

base64

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?

like image 345
Thomas Schmidt Avatar asked Mar 06 '16 15:03

Thomas Schmidt


People also ask

How do I display Base64 in HTML?

Images encoded with Base64 can be embedded in HTML by using the <img> tag.

What is Data Image PNG Base64?

data:image/png;base64 tells the browser that the data is inline, is a png image and is in this case base64 encoded. The encoding is needed because png images can contain bytes that are invalid inside a HTML document (or within the HTTP protocol even).


2 Answers

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">
like image 51
clarity123 Avatar answered Sep 23 '22 10:09

clarity123


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.

like image 41
wong2 Avatar answered Sep 20 '22 10:09

wong2