Embedding JPEG/PNG images into HTML and CSS data URLs
Posted: (EET/GMT+2)
Sometimes, you need to embed images into HTML pages for easy loading. For instance, you might have a Windows Phone application that needs to display off-line help data, and you want to include a couple of images, too.
Surely, you could have all the images as separate files and instruct the web browser component (such as WebView). However, especially for small needs, it's often easier to embed the images as inline images into the HTML (or CSS) code using "data URLs".
Data URLs have already been made as RFC documents in 1998, so this is an old technique, but nonetheless useful. Here's an example of a data URL:
data:[][;base64],
Here, the "mediatype" marker is replaced with the MIME type of the image in question, such as "image/jpeg", "image/png" or "image/gif".
With this URL in place, you can then create HTML "img" tags like this, specifying the data URL as the source attribute value:
<img src="data:image/gif;base64,R0lGO...
To convert an existing image to a Data URL, you can use useful web sites like this or this.
Note that in addition to the "img" URLs shown above, you can also use Data URLs in CSS background images like this:
.my-embedded-image {
width: 200px;
height: 150px;
background-image: url('data:image/png;base64,iVBORw0KGg...
}
Happy hacking!