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
Example:
<img src="data:image/gif;base64, iVBORw0KGgoAAAANSUhEUgAAABYAAAAQCAIAAACdjxhxAAAC7mlDQ1BJQ0MgUHJvZmlsZQAAeAGF VM9rE0EU/jZuqdAiCFprDrJ4kCJJWatoRdQ2/RFiawzbH7ZFkGQzSdZuNuvuJrWliOTi0SreRe2h B/+AHnrwZC9KhVpFKN6rKGKhFy3xzW5MtqXqwM5+8943731vdt8ADXLSNPWABOQNx1KiEWlsfEJq /IgAjqIJQTQlVdvsTiQGQYNz+Xvn2HoPgVtWw3v7d7J3rZrStpoHhP1A4Eea2Sqw7xdxClkSAog8 36Epx3QI3+PY8uyPOU55eMG1Dys9xFkifEA1Lc5/TbhTzSXTQINIOJT1cVI+nNeLlNcdB2luZsbI EL1PkKa7zO6rYqGcTvYOkL2d9H5Os94+wiHCCxmtP0a4jZ71jNU/4mHhpObEhj0cGDX0+GAVtxqp +DXCFF8QTSeiVHHZLg3xmK79VvJKgnCQOMpkYYBzWkhP10xu+LqHBX0m1xOv4ndWUeF5jxNn3tTd 70XaAq8wDh0MGgyaDUhQEEUEYZiwUECGPBoxNLJyPyOrBhuTezJ1JGq7dGJEsUF7Ntw9t1Gk3Tz+ KCJxlEO1CJL8Qf4qr8lP5Xn5y1yw2Fb3lK2bmrry4DvF5Zm5Gh7X08jjc01efJXUdpNXR5aseXq8 muwaP+xXlzHmgjWPxHOw+/EtX5XMlymMFMXjVfPqS4R1WjE3359sfzs94i7PLrXWc62JizdWm5dn /WpI++6qvJPmVflPXvXx/GfNxGPiKTEmdornIYmXxS7xkthLqwviYG3HCJ2VhinSbZH6JNVgYJq8 9S9dP1t4vUZ/DPVRlBnM0lSJ93/CKmQ0nbkOb/qP28f8F+T3iuefKAIvbODImbptU3HvEKFlpW5z rgIXv9F98LZua6N+OPwEWDyrFq1SNZ8gvAEcdod6HugpmNOWls05Uocsn5O66cpiUsxQ20NSUtcl 12VLFrOZVWLpdtiZ0x1uHKE5QvfEp0plk/qv8RGw/bBS+fmsUtl+ThrWgZf6b8C8/UXAeIuJAAAA CXBIWXMAAAsTAAALEwEAmpwYAAAARUlEQVQ4EWP8//8/A2WABaidkRHdjP//oUKMjIQtYELXTTp/ 1AhEmDGCIxUjShAKCLMGR3BCkhZ6+hlNWoTjD6sKKkQqAEwMDSGRs5xiAAAAAElFTkSuQmCC" 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:
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
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.
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.
Excellent tip!