【发布时间】:2011-12-31 08:44:51
【问题描述】:
我尝试将 svg 转换为 PNG。 svg 文档作为Inputstream 来自服务器。
首先,我将 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());
【问题讨论】:
-
您确认
streamBytes是正确的吗?这是您尝试保存到磁盘的完全相同的字节数组吗? -
@jon-skeet 正如我所说,如果我在磁盘上保存为 svg。效果很好。
-
我创建了一个 svg。然后转换成功。
尝试 { 文件文件 = 新文件("c:/a.svg"); if (!file.exists()) { file.createNewFile(); } 输出流输出 = 新文件输出流(文件); int 读取 = 0;字节[] 字节1 = 新字节[1024]; while ((read = svgStream.read(bytes1)) != -1) { out.write(bytes1, 0, read); } out.flush(); out.close(); } catch (IOException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } -
这里的
svgStream是什么?我的观点是,如果您使用与streamBytes不同的代码创建了文件,那么(比如说)IOUtils.toByteArray中可能会出现错误。IOUtils的实现在哪里? (有各种不同的开源项目,也可以是你自己的。) -
@jon-skeet 它来自 Apache
org.apache.commons.io.IOUtils;