文章目录
一、svg文件
1.1 svg介绍
SVG 意为可缩放矢量图形(Scalable Vector Graphics), 使用 XML 格式定义图像。因此对svg文件的操作,可以看做对xml文件的解析。svg基础知识可以参考svg教程,在此不做过多赘述。
1.2 svg文件操作
1.2.1 获取svg文件源码
读取svg文件并转换为字符串类型,可得到源码
public String svgOriginFile(MultipartFile file) throws IOException {
if (file != null) {
InputStream fileInput = file.getInputStream();
byte[] inputByte = new byte[fileInput.available()];
fileInput.read(inputByte);
String originFile = new String(inputByte, "UTF-8");
log.info("Get svg originFile [{}]", originFile);
fileInput.close();
return originFile;
}
return null;
}
1.2.2 获取svg文件宽高
读取svg的xml文件,获取svg文件的width、height属性
public Float svgSize(String originFile, String lengthName) throws IOException {
if (originFile != null && lengthName != null) {
Document doc = svgDocument(originFile);
Element element = doc.getDocumentElement();
String length = lengthReg(element.getAttribute(lengthName));
if (length == "" || length == null) {
int num = lengthName.equals("width") ? 2 : 3;
String viewBox = element.getAttribute("viewBox");
length = viewBox.split(" ")[num];
}
log.info("Svg {} size is {}", lengthName, length);
return Float.parseFloat(length);
}
return null;
}
public Document svgDocument(String originFile) throws IOException {
byte[] bytes = originFile.getBytes("utf-8");
ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
String parser = XMLResourceDescriptor.getXMLParserClassName();
SAXSVGDocumentFactory f = new SAXSVGDocumentFactory(parser);
Document doc = f.createDocument(null, inputStream);
return doc;
}
public String lengthReg(String str) {
//用正则表达式
String reg = "[^0-9]";
//Pattern类的作用在于编译正则表达式后创建一个匹配模式.
Pattern p = Pattern.compile(reg);
//Matcher类使用Pattern实例提供的模式信息对正则表达式进行匹配
Matcher m = p.matcher(str);
return m.replaceAll(