Borbin the 🐱

Web page with inline image

07 March, 2013


To add an image to a web page you use the img tag.
<img src="your-image.png" alt="your-image" />
Simple as that. But you need to use a binary file.

If you work on an embedded system, a html control with restrictions or simply need one plain html file, you can use images inline. The picture data will be encoded with text characters (base64) and added as a class:

<style type="text/css">
    .my-picture
    {
        background-image: url(data:image/png;base64, BASE64 DATA );
        height: 24px;
        width: 24px;
        display: block;
    }
</style>

Later on, you reference the picture class to display the image:

<div class="my-picture"></div>



sample

Here is a complete HTML sample:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>base64 image/png</title>
    <style type="text/css">
        .back-button
        {
            background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAADb0lEQVRIx52WT2hcVRTGf+fORJMgbYVEWv9uhEBaEpoMEem8DEKtm0qrWLCLItJFFyJIG5CIC12ni3ZhVRCKUEqJ1EVduNHUlzupm5k4Bptu1FUZwRhNTTMhNe9+LuYlDclMk/Rs3uXdc7/z3nfOd841mliUzz+GWbdBL3AQ6BTsAszgDjADjAkqSDd9sfhvIxxb/2IwiloEXcDbVn/eBaaAKjCXuu0E9gA9wA5Jv2F2EbjlvV9qGqBQKLgQwiGDYeAPpMsym3TOVeM4Dg18d5vUCxyX2fPAWZck1+IbN5Y3BCgUCi4kyRBwFLjki8ULbMOifP4tMzsl6bqTPoonJv4DcCu0hBAOAUcx+8zgS7ZrZqPAOTN7KTh3JIqi1tUAgq6UlksmXR0vFhe2i++9XxR8g/QpMATsBbC0Wj42eGrc+zcbHR4YGDAzywA2Pz+/PD09rQcFG8znvxDcw+wDl5ZiF9LlZgdCCC8mSTKcJMlJILPZ38jsipk9B/S6tM7vymyykXMul3saOAecAGpAsilf0hQwa9CXTUX0s3Ouug44A+SBkTRX79Rqte82owfAZTIzCmESeDkLdAIb6jwF/xB4RtIZ4FZbW1tHf39/M9xauVxeAIjjWINRVBV0ZAW77L5C19IyAuwHZszstVQfVi+6VQ2tXY8CX62hac7MdjnA6b5juqdW4JF1irdN1hsyAVjW4J+0t6xauVz+NZfLnaGujb2SvgbGgXsPoH5hnfB2CuaywF/Ak4VCwa3Lww/AMjBiZqeBP2u12vdbSXJqewxmHTAG9IQQdq/dLZVKSalUioHXgQBcaG9vP9Hd3W1b6EsdQB8w5gQVYEfaFTdYqVS6DZwGrgJPtLa2tmyhL+1L50c5i3RT8LvBceDbxv42IakkKZPNZpe3QM8xSVUzqxhAFEX7gU+QPsds1Hu/yENYFEWPmnRYMIzZu977H126Nw2cNbNTBq9GUdT2UODwCvWCOG8hVFbbtfd+ySXJNUnXgfdMemPb40A6DLwP/CQYHZ+YWNw4Mg8caAnOHQGGTPpFZleQplwmMxPHsRpWSz2hx5BeAM4LRovF4lLToZ9Oon1IJ83sWWAWmARuI91ZEVE69PuATklVzC5aCJWVL28aYE2gx4Eeq4McFHRYem0RzFk98JigbFAZ9/7vRjj/A6BAc6F41EmIAAAAAElFTkSuQmCC);
            height: 24px;
            width: 24px;
            display: block;
        }
    </style>
</head>
<body>
    <p>This is a back button</p>
    <div class="back-button"></div>
</body>
</html>

To convert between picture files and base64 data, you can use these PowerShell lines

From a file (for example 'p24.png') to base64 data:

$bin = Get-Content p24.png -Encoding Byte
$str = [System.Convert]::ToBase64String($bin)

From base64 data to a file (for example 'p24.png')

$str = "your BASE64 DATA"
$bin = [System.Convert]::FromBase64String($str)
Set-Content p24.png -Encoding Byte -Value $bin

Simple as that, but keep the image size small.