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 AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO 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:
data:<MIME-type>;base64,<data>
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).
Usage:
------
./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
/rhf/ge//3kf/Ub9/f3/b29oeHh/7LZv/0juazTktLS8WSLf//mf///yH5BAAAAAAALAAAAAAiABsAA
ASA8MlJq7046827/2AojiTVnI1xlFZjBisruU7tPCiqjg2h/L9KA2HgCQS5pE7UGLgwAhyCWWjYrrWE
owFgJqyEsDi82HZDja/jyGaXuV7rYE6fv8+gtLXA7/OtcCEGSoQMUyEHAQgAjI2OAAgBIwcGAZaXmAE
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.
Recent Comments