需要针对svg元素进行解析,并提取其中的颜色,首先需要知道svg中的颜色。针对svg中颜色的格式大致可以一般有纯色和渐变两种形式。对于渐变有分为:线性渐变和放射性渐变针对svg中的颜色支持16进制的格式,又可以支持RGB的格式,再者渐变颜色是以连接的形式存在的。提取渐变的颜色需要找到fill对应的dom节点
16进制颜色判断
private static boolean isHexColor(String value) {value = StringUtils.lowerCase(value);return Pattern.compile(HEX_COLOR).matcher(value).matches();}```
## RGB颜色判断
```javaprivate static boolean isRgbColor(String value) {value = StringUtils.lowerCase(value).replace(StringUtils.SPACE, StringUtils.EMPTY);return Pattern.compile(RGB_COLOR).matcher(value).matches();}```## 渐变颜色判断
```javaprivate static boolean isGradientColor(String value) {value = StringUtils.lowerCase(value).replace(StringUtils.SPACE, StringUtils.EMPTY);return Pattern.compile(GRADIENT_ID).matcher(value).matches();}
提取颜色代码
public static void getSvgColor(org.jsoup.nodes.Element svgElem, Set<String> colorSet) {String color = svgElem.attr("fill");if (isHexColor(color) || isRgbColor(color) || isGradientColor(color)) {colorSet.add(color);}Elements children = svgElem.children();for (org.jsoup.nodes.Element child : children) {getSvgColor(child, colorSet);}}
测试
public static void main(String[] args) throws Exception {String filePath = "/Users/qweasdzxc/Downloads/1.svg";try {List<String> lines = Files.readAllLines(Paths.get(filePath), StandardCharsets.UTF_8);String svgConent = String.join(System.lineSeparator(), lines);org.jsoup.nodes.Element svgElem = Jsoup.parse(svgConent).getElementsByTag("svg").get(0);HashSet hashSet = new HashSet<>();getSvgColor(svgElem, hashSet);System.out.println(hashSet);} catch (IOException e) {e.printStackTrace();}}