fiskeben
fiskeben

Reputation: 3467

Get empty image when transcoding SVG to PNG

I'm trying to generate an SVG image and then transcode it to PNG using Apache Batik. However, I end up with an empty image and I can't see why.

I use the Document from SVGDomImplementation as the base for my transcoding (to avoid writing the SVG to disk and loading it again). Here's an example:

  DOMImplementation domImpl = SVGDOMImplementation.getDOMImplementation();
  String namespace = SVGDOMImplementation.SVG_NAMESPACE_URI;
  Document document = domImpl.createDocument(namespace, "svg", null);

  //stuff that builds SVG (and works)

  TranscoderInput transcoderInput = new TranscoderInput(svgGenerator.getDOMFactory());
  PNGTranscoder transcoder = new PNGTranscoder();
  transcoder.addTranscodingHint(PNGTranscoder.KEY_WIDTH, new Float(svgWidth));
  transcoder.addTranscodingHint(PNGTranscoder.KEY_HEIGHT, new Float(svgHeight));

  try {
     File temp = File.createTempFile(key, ".png");
     FileOutputStream outputstream = new FileOutputStream(temp); 

     TranscoderOutput output = new TranscoderOutput(outputstream);

     transcoder.transcode(transcoderInput, output);
     outputstream.flush();
     outputstream.close();
     name = temp.getName();
  } catch (IOException ioex) {
     ioex.printStackTrace();
  } catch (TranscoderException trex) {
     trex.printStackTrace();
  }

My problem is that the resulting image is empty and I can't see why. Any hints?

Upvotes: 5

Views: 3826

Answers (1)

heycam
heycam

Reputation: 2206

I think it depends on how you're creating the SVG document. What are you using svgGenerator for (which I assume is an SVGGraphics2D)?

TranscoderInput transcoderInput = new TranscoderInput(svgGenerator.getDOMFactory());

If you've built up the SVG document in document, then you should pass it to the TranscoderInput constructor.

This page has an example of rasterizing an SVG DOM to a JPEG.

Upvotes: 1

Related Questions