Java: Loading a SVG into a BufferedImage

Unfortunately Java does not support SVG by default. But there is a great Apache Project aiming just for this purpose called batik.

Although the reference and documentation is pretty well, it does not cover loading an SVG and just saving it as a BufferedImage.

Here’s an example of how I did it:

Write a simple Transcoder

class BufferedImageTranscoder extends ImageTranscoder
{
  @Override
  public BufferedImage createImage(int w, int h)
  {
    BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
    return bi;
  }
 
  @Override
  public void writeImage(BufferedImage img, TranscoderOutput output)
  {
    this.img = img;
  }
 
  public BufferedImage getBufferedImage()
  {
    return img;
  }
  private BufferedImage img = null;
}

Using the Transcoder

  public static BufferedImage loadImage(File svgFile, float width, float height)
  {
    BufferedImageTranscoder imageTranscoder = new BufferedImageTranscoder();
 
    imageTranscoder.addTranscodingHint(PNGTranscoder.KEY_WIDTH, width);
    imageTranscoder.addTranscodingHint(PNGTranscoder.KEY_HEIGHT, height);
 
    TranscoderInput input = new TranscoderInput(svgFile);
    imageTranscoder.transcode(input, null);
 
    return imageTranscoder.getBufferedImage();
  }

This entry was posted in Java and tagged , , , , . Bookmark the permalink.

One Response to Java: Loading a SVG into a BufferedImage

  1. Tyron says:

    Funny, I just got in contact with batik as well recently, for converting browser generated charts in svg. Though I avoided its use by converting the svg to a canvas with the js lib canvg, which in return can be saved as png directly.

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">