如何即时将 SVG 转换为 PNG
我尝试将 svg 转换为 PNG。 svg 文档作为输入流来自服务器。
首先,我将 svg 流转换为字节数组:
byte[] streamBytes = IOUtils.toByteArray(svgStream);
然后,我使用以下代码将字节转换为 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;
}
但是我通过“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)
注意:如果我将 svgstream 保存在磁盘上并使用以下带有 uri 构造函数的转码器输入,那么它就可以工作。但就我而言,我不想保存在磁盘上。
TranscoderInput input = new TranscoderInput(new File("c:/a.svg").toURI().toString());
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());
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我发现了问题。
我每次都会检查 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..