【svg】—— java解析svg的宽高属性

本文介绍了如何使用Java处理SVG格式的图像,包括读取SVG文件中的宽高属性,并提供了一个方法`resizeSvg`,用于替换SVG中的宽高值以适应新的尺寸需求。
摘要由CSDN通过智能技术生成

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;
    }
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值