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

How to embed base64 images in SVG

1 min read

svg file

When creating SVG files you can include images by several means using local images, external URLs, and using base64 images. This tutorial covers how base64 images can be included and why you would want to.

Why should I embed images as base64?

Embedding images as base64 content will decrease the number of requests required as the images are now part of the SVG 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.

How to embed base64 images in SVG

Step 1 Convert image to base64 string
There are several ways to do this. Here is a Java example.

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);
}

Step 2 Create an img tag with an empty src value

<image href="" alt="Description of the image" />

Step 3 Construct a data URI in the src attribute

  1. Add a data media type to match the original image
    <image href="data:image/jpeg;" alt="Description of the image" />
  2. Add a charset that matches that used in the encoding
    <image href="data:image/jpeg;charset=utf-8;" alt="Description of the image" />
  3. Add the base64 data you created previously
    <image href="data:image/jpeg;charset=utf-8;base64,<DATA>" alt="Description of the image" />


Are you a Developer working with PDF files?

Our developers guide contains a large number of technical posts to help you understand the PDF file Format.

Do you need to solve any of these problems?

Display PDF documents in a Web app
Use PDF Forms in a web browser
Convert PDF Documents to an image
Work with PDF Documents in Java
Kieran France Kieran France is a programmer for IDRSolutions in charge of there internal test suite. In his spare time he enjoys tinkering with gadgets and code.

Leave a Reply

Your email address will not be published. Required fields are marked *

IDRsolutions Ltd 2022. All rights reserved.