Kieran France Kieran France is a programmer for IDRSolutions in charge of internal Java testing. In his spare time he enjoys tinkering with gadgets and code.

How to display base64 images in HTML (Tutorial)

1 min read

man using laptop coding html

When creating HTML files you can display base64 images by several means using local images, external URLs, and by embedding the image as base64 content.
This tutorial covers how you can display base64 images in HTML by embedding them. If you’re working with SVGs, you can read our article on how to embed base64 images in SVG.

Man using computer to display base64 images in html

Embed to display base64 images in HTML?

Embedding images as base64 content will decrease the number of requests required as the images are now part of the HTML file. However, the base64 content will be between 20-25% larger than the image.

This means that this approach will be beneficial for small to medium images but large images would have a much larger impact on performance. Browsers must decode base64 images before they can render them. For large images, this decoding process can be lengthy and may slow down page rendering.

How to embed base64 images in HTML

  1. Convert image to base64 string. There are lots of ways to do this (Java example below).
  2. Create an img tag with an empty src value
  3. Construct a data URI in the src attribute
    • Add a data media type to match the original image
    • Add a charset that matches that used in the encoding
    • Add the base64 data you created previously

Here is Java code to create base64 image data…

final ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
//Can be any support image format
final String formatName = "jpg";
//Convert image data to Base64 and write date to the output stream
final BufferedImage image = ImageIO.read(new File("/path/to/file"));
ImageIO.write(image, formatName, Base64.getEncoder().wrap(os));
//Create Base64 string
final String base64 = os.toString(StandardCharsets.UTF_8.name());
} catch (final IOException ioe) {
throw new UncheckedIOException(ioe);
}

Add this to your HTML…

<img src="data:image/jpeg;charset=utf-8;base64,<DATA>" alt="Description of the image" />


Our software libraries allow you to

Convert PDF to HTML in Java
Convert PDF Forms to HTML5 in Java
Convert PDF Documents to an image in Java
Work with PDF Documents in Java
Read and Write AVIF, HEIC, WEBP and other image formats
Kieran France Kieran France is a programmer for IDRSolutions in charge of internal Java testing. In his spare time he enjoys tinkering with gadgets and code.