Embed pictures in HTML code with Base64 encoding

There are times when you do not want to reference a picture on a HTML page but you want the picture to be IN the HTML code. This can for example be if you are creating HTML to send in e-mails. Attaching a bunch of picture files does not always go well with mail software and spam filters.

The secret here is the “hidden” talents of the img tag which can read base64 encoded content. The syntax is:

<img src="data:{mime};base64,{data}" alt="My picture"/>

{Mime} is in ‘image/imagetype’ format (eg. ‘image/jpg’ or image/png) and {data} is the base64 encoded string

<img src="data:image/gif;base64, iVBORw0KGgoAAAANSUhEUgAAABYAAAAQCAIAAACdjxhxAAAC7mlDQ1BJQ0MgUHJvZmlsZQAAeAGF
 alt="Flag of Sweden"/>

Here the mime is ‘image/gif’ since the picture data is from a gif file. You can also use image/png and image/jpg.
When running the code above through a browser we get:
Flag of Sweden

A small picture of the flag of Sweden. Not much, but base64 encoded pictures tend to be quite large in string form 🙂

Tested on OS X 10.6.8 and Chrome 16 Beta

  1. Cool stuff! For smaller images this seems to work good for fewer HTTP requests. I’ve started using http://www.base64-decoder.com to encode my files into base64.

  2. I recommend http://base64image.org web tool to encode image to Base64 and back to Image. It supports drag and drop, multiple files and automatic CSS, HTML generation.

Leave a Comment

NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre lang="" line="" escaped="" cssfile="">

This site uses Akismet to reduce spam. Learn how your comment data is processed.