None

Using Batik to convert SVG to JPG

April 9, 2010

You can use the Batik library to convert from an SVG source to a JPG image file.

Java Code

Here's the code used to convert to SVG file that is held in memory as part of a JDom document, into a JPG file on disk.

Element lRootElement = lDocument.getRootElement();
Namespace lSvgNamespace = Namespace.getNamespace("http://www.w3.org/2000/svg");
Element lSvgElement = lRootElement.getChild("svg", lSvgNamespace);

XMLOutputter lXMLOutputter = new XMLOutputter();
lXMLOutputter.setFormat(Format.getPrettyFormat());

String lSvgXml = lXMLOutputter.outputString(lSvgElement);
String lTmpDir = System.getProperty("java.io.tmpdir");
String lSvgFilePath = lTmpDir + "/chart_" + lSerial + ".svg";

try
{
  FileOutputStream lFos = new FileOutputStream(lSvgFilePath);
  PrintWriter lPrintWriter = new PrintWriter(lFos);
  lPrintWriter.println("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
  lPrintWriter.println(lSvgXml);
  lPrintWriter.close();
}
catch (Exception lEx)
{
  throw new RuntimeException(lEx.getMessage(), lEx);
}

String lJpgImageFilePath = lTmpDir + "/chart_" + lSerial + ".jpg";
// convert SVG to JPG
try
{
  JPEGTranscoder lTranscoder = new JPEGTranscoder();

  // Set the transcoding hints.
  lTranscoder.addTranscodingHint(JPEGTranscoder.KEY_QUALITY, new Float(.8));

  // Create the transcoder input.
  TranscoderInput lInput = new TranscoderInput(new FileInputStream(lSvgFilePath));
  // Create the transcoder output.
  OutputStream lOutputStream = new FileOutputStream(lJpgImageFilePath);
  TranscoderOutput lOutput = new TranscoderOutput(lOutputStream);

  // Save the image.
  lTranscoder.transcode(lInput, lOutput);

  // Flush and close the stream.
 lOutputStream.flush();
 lOutputStream.close();
}
catch (Exception lEx)
{
  throw new RuntimeException(lEx.getMessage(), lEx);
}

Issues

I had problems with it producing a zero length JPG file. This was because my SVG didn't have the correct (or indeed any) namespace. I needed to add

xmlns="http://www.w3.org/2000/svg"

to my generated SVG to make it valid.

Tags: svg jpg batik