SVG(Scalable Vector Graphics)是一种基于XML的图像格式,用于描述二维矢量图形。用户在网页上展示高质量的矢量图形,svg图形可以无限放大或缩小而不会失真,保持清晰的边缘和线条。
java对于svg的处理其实比较麻烦,java需要依赖
解析svg的宽高属性
public static void main(String[] args) throws IOException {
String svgString = new String(Files.readAllBytes(Paths.get("/Users/qweasdzxc/Downloads/test.svg")), "utf-8");
String width = StringUtils.EMPTY;
String height = StringUtils.EMPTY;
try {
// 创建XML解析器
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource inputSource = new InputSource(new StringReader(svgString));
Document document = builder.parse(inputSource);
// 获取SVG的根元素
Element root = document.getDocumentElement();
// 获取SVG的宽高属性
width = root.getAttribute("width");
height = root.getAttribute("height");
} catch (Exception e) {
}
System.out.println(width + "___" + height);
}
替换宽高为指定数据
private static String resizeSvg(String svgStr, Integer newWidth, Integer newHeight) {
if (Objects.isNull(newHeight) || Objects.isNull(newWidth) || newHeight <= 0 || newWidth <= 0) {
return svgStr;
}
String pattern = "<svg[^>]*(?:\\s(width|height)=('|\")(\\d*(?:\\.\\d+)?)(?:px)?('|\"))[^>]*(?:\\s(width|height)=('|\")(\\d*(?:\\.\\d+)?)(?:px)?('|\"))[^>]*>";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(svgStr);
// 检查字符串中是否包含匹配的内容
if (m.find()) {
final String formatStr = "%s=\"%s\"";
svgStr = svgStr.replace(String.format(formatStr, m.group(1), m.group(3)),
String.format(formatStr, m.group(1), m.group(1).equals("height") ? newHeight : newWidth))
.replace(String.format(formatStr, m.group(5), m.group(7)),
String.format(formatStr, m.group(5), m.group(5).equals("height") ? newHeight : newWidth));
}
return svgStr;
}