如何实时将SVG转换为PNG

14

I try to convert an svg into PNG. the svg document is coming from a server as an Inputstream.

First, I convert the svg stream into byte array with:

 byte[] streamBytes = IOUtils.toByteArray(svgStream);

Then I convert the bytes into OutputStream(PNG) with the following code.

private ByteArrayOutputStream svgToPng(byte[] streamBytes)
                                            throws TranscoderException, IOException {
        PNGTranscoder t = new PNGTranscoder();
        TranscoderInput input = new TranscoderInput(new ByteArrayInputStream(streamBytes));
        ByteArrayOutputStream ostream = new ByteArrayOutputStream();
        TranscoderOutput output = new TranscoderOutput(ostream);

        t.transcode(input, output);

        ostream.flush();
        // ostream.close();
        return ostream;
    }

But i get null pointer exception by "t.transcode(input, output);"

org.apache.batik.transcoder.TranscoderException: null
Enclosed Exception:
Premature end of file.
graphdata : null
    at org.apache.batik.transcoder.XMLAbstractTranscoder.transcode(XMLAbstractTranscoder.java:136)
    at org.apache.batik.transcoder.SVGAbstractTranscoder.transcode(SVGAbstractTranscoder.java:156)

Note: If i save the svgstream on th disk and use the following transcoderinput with uri constructor, then it works. But in my case i don't want to save on the disk.

TranscoderInput input = new TranscoderInput(new File("c:/a.svg").toURI().toString());


你已经验证了 streamBytes 是否正确吗?那是不是你尝试保存到磁盘的完全相同的字节数组? - Jon Skeet
@jon-skeet 正如我所说,如果我将其保存为SVG格式到磁盘上,它就能完美运行。 - Kayser
我创建了一个SVG文件,然后成功地进行了转换。<br>尝试 { File file = new File("c:/a.svg"); if (!file.exists()) { file.createNewFile(); } OutputStream out = new FileOutputStream(file); int read = 0; byte[] bytes1 = new byte[1024]; while ((read = svgStream.read(bytes1)) != -1) { out.write(bytes1, 0, read); } out.flush(); out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } - Kayser
这里的 svgStream 是什么?我的意思是,如果您使用不同于 streamBytes 的代码创建了文件,则在(例如)IOUtils.toByteArray 中可能会出现错误。IOUtils 的实现在哪里?(有各种不同的开源实现,或者它可能是您自己的实现。) - Jon Skeet
@jon-skeet 这是来自Apache的 org.apache.commons.io.IOUtils; - Kayser
好的。我认为那应该没问题... - Jon Skeet
1个回答

4
我找到了问题所在。 每次检查svgstream是否正常时,我都会使用我的评论中的代码创建一个SVG文件来查看它是否正常。逻辑上,这会消耗流。最终没有真正的流导致了异常。 感谢大家的帮助。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接