99网
您的当前位置:首页【svg】—— java提取svg中的颜色

【svg】—— java提取svg中的颜色

来源:99网
 需要针对svg元素进行解析,并提取其中的颜色,首先需要知道svg中的颜色。针对svg中颜色的格式大致可以一般有纯色和渐变两种形式。对于渐变有分为:线性渐变和放射性渐变
 针对svg中的颜色支持16进制的格式,又可以支持RGB的格式,再者渐变颜色是以连接的形式存在的。提取渐变的颜色需要找到fill对应的dom节点
    ![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/7254e8f46a1e404eb141ebb417a57e19.png#pic_center)

16进制颜色判断

private static boolean isHexColor(String value) {
        value = StringUtils.lowerCase(value);
        return Pattern.compile(HEX_COLOR).matcher(value).matches();
    }
    ```
## RGB颜色判断
```java
    private static boolean isRgbColor(String value) {
        value = StringUtils.lowerCase(value).replace(StringUtils.SPACE, StringUtils.EMPTY);
        // 此处只做简单的数值校验,不做范围的验证
        return Pattern.compile(RGB_COLOR).matcher(value).matches();
    }
    ```
    
## 渐变颜色判断
```java
  private 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 {
            // 使用Files.readAllLines读取文件的所有行,使用UTF-8编码
            List<String> lines = Files.readAllLines(Paths.get(filePath), StandardCharsets.UTF_8);

            // 将字符串列表转换为一个单一的String,每行之间用系统默认的换行符分隔
            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();
        }
    }

因篇幅问题不能全部显示,请点此查看更多更全内容