Colen
Colen

Reputation: 13908

Is it safe to use <a href="data; ..."> to display images?

I've learned that it's possible to embed an image in an HTML page like so, instead of linking to a separate image file:

<a href="data:image/png;base64,...(blah blah base64-encoded png goes here)..."
  width="70" height="38" alt="image embedded using base64 encoding!"></a>

Is this "safe", as in will all modern browsers be able to view the image, as long as I stick to common formats like PNG/JPG? Are there any downsides, other than base64-encoding the image increasing the image size by a bit?

Thanks.

Upvotes: 17

Views: 60617

Answers (2)

700 Software
700 Software

Reputation: 87773

All modern browsers should be able to view these types of images. I have not verified, but this capability has been around for a good while and is probably widely supported.

But you also asked for downsides. One downside is that it is common that HTML markup is dynamically generated and therefore cannot be cached.

  • If you have static html pages then your html is cachable in that case using data urls might even be better for performance if the images are not too big.
  • If you are including this in any dynamic html (php, cgi, jsp, shtml, just about anything other than xml,html,xhtml,htm) Then there will be zero caching and therefore the images will have to load each time instead of just the first time.

More downsides that probably don't relate

  • Also on a general note, base64 takes exactly one and a third times as much space as having the file straight. That is why for larger images it might be a little less good even if it is a static html page. But if your webserver supports gzip, then it will not quite take an entire third longer for the images.
  • And even if it is static html, if you use a data url (can be called inlining your images), the whole page will not display before the images like normal. But for pages with small images that should not matter
  • And finally, if you have large images, you would might want to do this because the browser would not be able to use multiple download connections like it normally does.
  • Also @Oded's downsides (and upside) that I did not think of

Upvotes: 5

Oded
Oded

Reputation: 499002

Yes, this is safe - all major browsers support the data URI scheme.

One downside is that if you use the same image a number of times in the page, it will be encoded several times vs downloaded once.

Another is the size limit imposed by some browsers (IE 8 only allows up to 32k).

You can also use this in CSS to mitigate the download issue.

Upvotes: 22

Related Questions