项目业务场景中前端合成的文件格式是svg的,但在java中不能像图片那样用IO流读写合成。
转自 https://www.cnblogs.com/chenjy1225/p/9662218.html
此文中介绍了如何将svg转成png,亲测有效。maven的依赖要使用博主给出的版本,新版本会报各种类缺失的异常。
<!-- svg 转 png -->
<dependency>
<groupId>batik</groupId>
<artifactId>batik-svggen</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>batik</groupId>
<artifactId>batik-awt-util</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>batik</groupId>
<artifactId>batik-bridge</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>batik</groupId>
<artifactId>batik-css</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>batik</groupId>
<artifactId>batik-dom</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>batik</groupId>
<artifactId>batik-gvt</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>batik</groupId>
<artifactId>batik-parser</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>batik</groupId>
<artifactId>batik-script</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>batik</groupId>
<artifactId>batik-svg-dom</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>batik</groupId>
<artifactId>batik-transcoder</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>batik</groupId>
<artifactId>batik-util</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>batik</groupId>
<artifactId>batik-xml</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>xerces</groupId>
<artifactId>xercesImpl</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>xml-apis</groupId>
<artifactId>xmlParserAPIs</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>org.axsl.org.w3c.dom.svg</groupId>
<artifactId>svg-dom-java</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>xml-apis</groupId>
<artifactId>xml-apis</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>org.w3c.css</groupId>
<artifactId>sac</artifactId>
<version>1.3</version>
</dependency>
public static void convertSvg2Png(File svg, File png) throws IOException,TranscoderException
{
InputStream in = new FileInputStream(svg);
OutputStream out = new FileOutputStream(png);
out = new BufferedOutputStream(out);
Transcoder transcoder = new PNGTranscoder();
try {
TranscoderInput input = new TranscoderInput(in);
try {
TranscoderOutput output = new TranscoderOutput(out);
transcoder.transcode(input, output);
} finally {
out.close();
}
} finally {
in.close();
}
}
public static void main(String args[]){
File f=new File("E:/Pinterest_pinterest30.svg");
File destFile=new File("E:/Pinterest_pinterest30.png");
try {
convertSvg2Png(f, destFile);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TranscoderException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
转换效果,原文可见。