简体   繁体   English

如何在运行中将SVG转换为PNG

[英]How to convert SVG into PNG on-the-fly

I try to convert an svg into PNG. 我尝试将svg转换为PNG。 the svg document is coming from a server as an Inputstream . svg文件来自服务器作为Inputstream

First, I convert the svg stream into byte array with: 首先,我将svg流转换为字节数组:

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

Then I convert the bytes into OutputStream (PNG) with the following code. 然后我使用以下代码将字节转换为OutputStream (PNG)。

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); " 但我通过“ t.transcode(input, output); ”得到空指针异常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. 注意:如果我将svgstream保存在磁盘上并使用以下transcoderinput和uri构造函数,那么它可以工作。 But in my case i don't want to save on the disk. 但在我的情况下,我不想保存在磁盘上。

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

I found the problem. 我发现了这个问题。

I checked each time if the svgstream is ok or not. 我每次检查svgstream是否正常。 To see if it is ok, I created each time an SVG file with the code in my comment. 为了查看它是否正常,我每次创建一个SVG文件,其中包含我的评论中的代码。 Logically it consumed the stream. 逻辑上它消耗了流。 There was no real stream at the end. 最后没有真正的流。 It caused the Exception. 它导致了异常。 Thanks to all.. 谢谢大家..

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM