Kay*_*ser 14 java svg png batik
我尝试将svg转换为PNG.svg文件来自服务器Inputstream
.
首先,我将svg流转换为字节数组:
byte[] streamBytes = IOUtils.toByteArray(svgStream);
Run Code Online (Sandbox Code Playgroud)
然后我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;
}
Run Code Online (Sandbox Code Playgroud)
但我通过" 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)
Run Code Online (Sandbox Code Playgroud)
注意:如果我将svgstream保存在磁盘上并使用以下transcoderinput和uri构造函数,那么它可以工作.但在我的情况下,我不想保存在磁盘上.
TranscoderInput input = new TranscoderInput(new File("c:/a.svg").toURI().toString());
Run Code Online (Sandbox Code Playgroud)
我发现了问题。
我每次都会检查 svgstream 是否正常。为了看看是否可以,我每次都使用评论中的代码创建一个 SVG 文件。从逻辑上讲,它消耗了流。最后没有真正的流。它导致了异常。谢谢大家..