Home > html, python > Embed images in HTML pages

Embed images in HTML pages

If you have a web page with some images, usually the images are stored in separate files. Would it be possible to include all the images in the HTML file, making a self-contained file?

Well, yes, with the help of the data URI scheme. “The data URI scheme is a URI scheme that provides a way to include data in-line in web pages as if they were external resources.

Example: (borrowed from here)

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />

As you can see, the data can contain newline characters. If you put it an HTML file and open it with your browser, you’ll see a small red dot.

General format:


Script to produce it

I made a little script that can do this BASE64 encoding of image files. You can download it from here (img_to_base64.py).


./img_to_base64.py <image_file>
    By default, the data is nested in an HTML tag and the output
    is wrapped. These settings can be customized.
    The output is printed to the standard output.
Sample output:

<img class='inline-image' src='data:image/gif;base64,R0lGODlhIgAbAPMPAGxsbNbW1v
7Mpydnp+goaKjFBEAOw==' />

Project idea

It could be interesting to write a script that transforms an HTML file into a self-contained file, i.e. replace all occurrences of ‘<img src="some_image" />‘ with an embedded base64 encoded data.

Ref.: I met this image inlining technique in justinvh’s Markdown-LaTeX project.

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: