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 Skeetfile.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(); }
- KaysersvgStream
是什么?我的意思是,如果您使用不同于streamBytes
的代码创建了文件,则在(例如)IOUtils.toByteArray
中可能会出现错误。IOUtils
的实现在哪里?(有各种不同的开源实现,或者它可能是您自己的实现。) - Jon Skeetorg.apache.commons.io.IOUtils;
- Kayser