如何在运行中将SVG转换为PNG [英] How to convert SVG into PNG on-the-fly

查看:215
本文介绍了如何在运行中将SVG转换为PNG的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试将svg转换为PNG。 svg文件来自服务器,作为 Inputstream


首先,我将svg流转换为字节数组:

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);

然后我将字节转换为 OutputStream ( PNG),代码如下。

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;
    }

但我通过 t得到空指针异常。转码(输入,输出);

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)

注意:如果我将svgstream保存在磁盘上并使用以下transcoderinput和uri构造函数,然后它的工作原理。但在我的情况下,我不想保存在磁盘上。

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());


推荐答案

我发现了问题。


我每次检查svgstream是否正常。为了查看它是否正常,我每次创建一个SVG文件,其中包含我的评论中的代码。逻辑上它消耗了流。最后没有真正的流。它导致了异常。
感谢所有..

I found the problem.

I checked each time if the svgstream is ok or not. To see if it is ok, I created each time an SVG file with the code in my comment. Logically it consumed the stream. There was no real stream at the end. It caused the Exception. Thanks to all..

这篇关于如何在运行中将SVG转换为PNG的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆