batik svg转png

本文介绍了如何利用Java库Batik将 Scalable Vector Graphics (SVG) 文件转换为Portable Network Graphics (PNG) 格式的图像,详细阐述了转换过程和技术要点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.batik.apps.rasterizer.DestinationType;
import org.apache.batik.apps.rasterizer.SVGConverter;
import org.apache.batik.dom.svg.SAXSVGDocumentFactory;
import org.apache.batik.util.XMLResourceDescriptor;
import org.w3c.dom.Document;
public class Test {
public Document createDocument(InputStream in) {
Document doc = null ;
try {
// Create a new svg document.
String parser = XMLResourceDescriptor.getXMLParserClassName();
SAXSVGDocumentFactory f = new SAXSVGDocumentFactory(parser);
doc = f.createSVGDocument(null, in);

} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
return doc;
}
public static void main(String[] args) throws Exception {


String svgPath = "D:\\input.svg";
String pngPath = "D:\\test.png";



Test rasterizer = new Test();
InputStream in = new FileInputStream(new File(svgPath));
Document svgXmlDoc = rasterizer.createDocument(in);
// Save this SVG into a file (required by SVG -> PNG transformation process)
File svgFile = File.createTempFile("graphic-", ".svg");
Transformer transformer = TransformerFactory.newInstance().newTransformer();
DOMSource source = new DOMSource(svgXmlDoc);
FileOutputStream fos = new FileOutputStream(svgFile);
try {
transformer.transform(source, new StreamResult(fos));
} finally {
fos.close();
}
// Convert the SVG into PNG
File outputFile =new File(pngPath);
SVGConverter converter = new SVGConverter();
converter.setDestinationType(DestinationType.PNG);
converter.setSources(new String[]{svgFile.toString()});
converter.setDst(outputFile);
converter.execute();
}
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值