An HTML file is easier to share when its images travel with it. On Linux or macOS, you can encode a small PNG as Base64 and embed it in the HTML so a browser can display the image from that one file.

An <img> element can use a data: URL in its src attribute. For a PNG, image/png identifies the format, base64 tells the browser to decode the text, and the comma marks where the encoded bytes begin.

Base64 adds about a third to the image's size before compression. When several pages embed the same image, each HTML file carries its own copy of that text.

Steps to embed a Base64 image in HTML:

  1. Create an empty test folder named preview.
  2. Copy a small PNG as badge.png into the preview folder.
  3. Encode badge.png from a terminal in the preview folder.
    base64 < badge.png | tr -d '\n' > badge-base64.txt

    tr removes line breaks so badge-base64.txt contains one line of Base64 text.

  4. Enter the following HTML in a new plain-text document in your text editor.
    <!doctype html>
    <html lang="en">
    <head>
      <meta charset="utf-8">
      <title>Embedded image</title>
    </head>
    <body>
      <img src="data:image/png;base64,BASE64_DATA" alt="">
    </body>
    </html>
  5. Replace BASE64_DATA with the entire contents of badge-base64.txt.

    The encoded text starts immediately after the comma and ends at the closing quote of src.

  6. Describe the image in the alt attribute.

    For the pictured PNG, the description is White check mark on a blue square. A purely decorative image can keep alt="".

  7. Save the document as badge.html in the preview folder.
  8. Verify in your text editor that data:image/png;base64, is the prefix of the <img> element's src value in the saved badge.html.

    A filename in src points to a separate file.

  9. Open preview/badge.html in desktop Chrome using its full file:/// address.
  10. Verify that the PNG is visible on the Embedded image page.

    The pictured page shows a white check mark on a blue square. If you see a broken image icon or only the description, check the comma and the full Base64 string in src.

Share this guide