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

标签 java png svg batik transcode

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

我使用 SVGDomImplementation 中的文档作为转码的基础(以避免将 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();
  }

我的问题是生成的图像是空的,我不明白为什么。有什么提示吗?

最佳答案

我认为这取决于您创建 SVG 文档的方式。您使用 svgGenerator 做什么(我假设是 SVGGraphics2D)?

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

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

This page有一个将 SVG DOM 栅格化为 JPEG 的示例。

关于java - 将 SVG 转码为 PNG 时获取空图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2369779/

相关文章:

java - TIntSet 中的最高和最低元素?

java - 如何将Jsonelement解析为Array?

android - Android 中的位图 : Size of resources for displaying as 50dp

image - 你更喜欢哪个?用于图形和图表的 SVG、HTML5 或 regen'd-PNG?

php - 如何将图像保存到从 iOS 应用程序接收到的文件中,PHP 编码为十六进制?

javascript - Safari 中的 html2canvas 不在 SVG 路径上呈现 Javascript style.fill

java - 单击按钮后关闭警报对话框

java - JSF 身份验证和授权

javascript - d3.js(maps) svg 元素在将它们添加到现有 svg 元素之上时不出现

javascript - 动态更改 SVG 元素后对其进行动画处理