Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 950
fiskeben Avatar asked Nov 15 '22 12:11

fiskeben


1 Answers

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.

like image 193
heycam Avatar answered Dec 04 '22 22:12

heycam