java解析svg
涉及jar包
<dependency>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>batik-all</artifactId>
<version>1.9.1</version>
</dependency>
svg工具
import org.apache.batik.anim.dom.SAXSVGDocumentFactory;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.PNGTranscoder;
import org.apache.batik.util.XMLResourceDescriptor;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
public class SvgUtil {
/**
* 将svg转换成字符串
* @param svgPath
* @return
*/
public static String toString(String svgPath) {
String parser = XMLResourceDescriptor.getXMLParserClassName();
SAXSVGDocumentFactory f = new SAXSVGDocumentFactory(parser);
try {
Document doc = f.createDocument(svgPath);
Element documentElement = doc.getDocumentElement();
TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transformer = transFactory.newTransformer();
StringWriter buffer = new StringWriter();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.transform(new DOMSource(documentElement), new StreamResult(buffer));
return buffer.toString();
}
catch (Exception e) {
e.printStackTrace();
}
return "";
}
/**
* svg转png
* @param inputStream
* @return
*/
public static byte[] toPng(InputStream inputStream) {
PNGTranscoder transcoder = new PNGTranscoder();
TranscoderInput input = new TranscoderInput(inputStream);
ByteArrayOutputStream outputStream = null;
try {
outputStream = new ByteArrayOutputStream();
TranscoderOutput output = new TranscoderOutput(outputStream);
transcoder.transcode(input, output);
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (outputStream != null) {
try {
outputStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
return outputStream.toByteArray();
}
}