Creating inline (embedded) PNG images

Sometimes it's necessary, or nice, to be able to directly embed an image in code. Like a modern form of ASCII art, you then don't have to distribute icons and images with your source, because the image is in the source itself. The method uses Base64 encoding. See the RFC for Data URI.

"Base64" format used by MIME-encoded documents such as electronic mail messages with embedded images and audio files.

To convert a PNG (for example) image to Base64, you will need some utility. base64 is an open-source converter that does just this.

Do the configure, compile jig:

$ ./configure
$ make
$ sudo make install

Then encode your image:

base64 -e my_image.png my_image.png.base64

Open the my_image.png.base64 file in a text editor and then copy it into your code. An example is shown below, written in Javascript.

const png_image_src = 'data:image/png;base64,'+
'Oqnd2VLWaOX0x7ftwZzZlIjGxr7gxanLkdfu1FumybHSsJ3Cutbyx4S9fm2paMrq0Lfo1L/a' +
'o6PHiozL11aZJpnW2oG0ZLTcm5zjvovbvM3qtcror2q5vUaIRHLGZWWkR0aQGSR/BYy5baHY' +
'imrbd/z+/HO9bPb69m29xHy8c2OeMUGJPZDThZPPi3ivdGazzZbBgCuCEd3x2jaICs7ksqLZ' +
'mTp/N6zwtWu/YLDWvZHHeqLS0affzKfvsWDYpn7CvJHJh0+cSGWbY6PQka/Xkvj894W2a4DQ' +
'qIrDhF+hQ8fexJDN24PYgYGzWnXJy6zXpp3Fm5jCg37NdI++dWejWmCwVnSrT6nuyTuLELvh' +
'pV2gO6DSwI3qnd3wv6rQxK/fz1OZxrTvtaLim3rRr+bv5TuCN+jw557FiK7NlWzRkHDGhHLd' +
'fnHWmm2zx7Xe1m21zW65z9Ts0HTHaHrGb3vJb3yvVbTaxVGUTITLtV6w0////94DUpYAAACA' +
'dFJOU///////////////////////////////////////////////////////////////////' +
'////////////////////////////////////////////////////////////////////////' +
'//////////////////////////////8AOAVLZwAAAQxJREFUeNpiqAcCc87wcuVKTl4Qm6G+' +
'XstKOU6eu9ouxNbICySgZajBzluWUuzgkOyqpwMUsNJIEuQVYWUNkOCysxeqZzBXZk+z4RCV' +
'0WcUtjRgUE4Kz5Plq0vVzWAJkoy0zGKokDeU4+JjYWHRr+KJVhVTYjDylMn34WPJzeXhiRBX' +

var my_link = document.createElement('a');
my_link.title = "Go to"
my_image = document.createElement('img');
my_image.src = png_image_src;
route_image.border = 0;
my_link.href = "";

document.body.insertBefore(my_link, document.body.lastChild);

About this article

written on
posted in ProgrammingWebOpen-SourceJavascriptHowto Back to Top

About the Author

Andrew Turner is an advocate of open standards and open data. He is actively involved in many organizations developing and supporting open standards, including OpenStreetMap, Open Geospatial Consortium, Open Web Foundation, OSGeo, and the World Wide Web Consortium. He co-founded CrisisCommons, a community of volunteers that, in coordination with government agencies and disaster response groups, build technology tools to help people in need during and after a crisis such as an earthquake, tsunami, tornado, hurricane, flood, or wildfire.