将SVG转码为PNG时获取空图像

fis*_*ben 5 java transcode svg png batik

我正在尝试生成一个SVG图像,然后使用Apache Batik将其转码为PNG.但是,我最终得到一个空图像,我不明白为什么.

我使用SVGDomImplementation中的Document作为我的代码转换的基础(避免将SVG写入磁盘并再次加载).这是一个例子:

  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();
  }
Run Code Online (Sandbox Code Playgroud)

我的问题是结果图像是空的,我不明白为什么.任何提示?

hey*_*cam 1

我认为这取决于您如何创建 SVG 文档。你用什么svgGenerator(我假设是一个SVGGraphics2D)?

TranscoderInput transcoderInput = new TranscoderInput(svgGenerator.getDOMFactory());
Run Code Online (Sandbox Code Playgroud)

如果您已经在 中构建了 SVG 文档document,那么您应该将其传递给TranscoderInput构造函数。

此页面有一个将 SVG DOM 光栅化为 JPEG 的示例。