SLD supports the use of external icons, such as bitmap images or vector graphics in many formats, such as PNG, JPEG and SVG. To use an external icon in an SLD styling file, you must define it in an ExternalGraphic element. You can define the graphic in several ways:

  • Refer to it by using:

    • A location on the Internet:

      <ExternalGraphic>
        <OnlineResource xlink:type="simple" xlink:href="https://upload.wikimedia.org/wikipedia/commons/1/1d/Placemark-globe.svg"/>
        <Format>image/svg+xml</Format>
      </ExternalGraphic>
    • An absolute path on disk:

      <ExternalGraphic>
        <OnlineResource xlink:type="simple" xlink:href="C:/Images/obstacles/crane.png"/>
        <Format>image/png</Format>
      </ExternalGraphic>
    • A relative path on disk. Make sure that the folder holding the files is in the classpath of your application:

      <ExternalGraphic>
        <OnlineResource xlink:type="simple" xlink:href="./obstacles/crane.png"/>
        <Format>image/png</Format>
      </ExternalGraphic>
    • A dynamic path, relying on a property of the data that needs styling:

      <ExternalGraphic>
        <OnlineResource xlink:type="simple" xlink:href="./obstacles/${obstacleTypeProperty}.png"/>
        <Format>image/png</Format>
      </ExternalGraphic>
  • Embed it using an InlineContent element:

    <ExternalGraphic>
    <InlineContent encoding="base64">...(Base64-encoded String representation of the icon)</InlineContent>
    <Format>image/png</se:Format>
    </ExternalGraphic>

You can rely on Apache Batik’s Base64EncoderStream (included as third-party library) to generate a Base64 String for your icon. The following example shows its usage:

// Read the icon into an image.
BufferedImage image = ImageIO.read(new File("pathToIconFile"));
// Encode the image as PNG into a Base64 byte stream.
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
ImageIO.write(image, "png", new Base64EncoderStream(byteStream));
// Turn the Base64 byte stream into a String. Make sure to remove any carriage returns.
String base64String = new String(byteStream.toByteArray()).replaceAll("[\n\r]", "");