用Java读取svg路径数据的最简单方法? [英] Easiest way to read in svg path data with Java?

查看:599
本文介绍了用Java读取svg路径数据的最简单方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望使用svg图像并解析/处理不同的路径以进行自定义转换.在Java中,最简单的方法是简单地提取路径数据?我正在查看apache xmlgraphics/batik包,但是如何返回路径类型和参数并不是很明显.有什么建议吗?

I'm looking to consume an svg image and parse/process the different paths to do a custom conversion. What is the easiest way, in Java, to simply extract the path data? I was looking at the apache xmlgraphics/batik packages, but it's not real obvious how to return the path types and parameters. Any suggestions?

推荐答案

要简单地提取path数据,可以使用XPath.

To simply extract the path data you can use XPath.

假设您有此SVG,并且要提取所有path数据(从两个path元素中提取):

Suppose you have this SVG and you want to extract all the path data (from both path elements):

<svg>
  <rect x="1" y="1" width="1198" height="598"
        fill="none" stroke="blue" stroke-width="1" />

  <path d="M200,300 Q400,50 600,300 T1000,300"
        fill="none" stroke="red" stroke-width="5"  />
  <g fill="black" >
    <circle cx="200" cy="300" r="10"/>
    <circle cx="600" cy="300" r="10"/>
    <circle cx="1000" cy="300" r="10"/>
  </g>
  <g fill="#888888" >
    <circle cx="400" cy="50" r="10"/>
    <circle cx="800" cy="550" r="10"/>
  </g>
  <path d="M200,300 L400,50 L600,300 L800,550 L1000,300"
        fill="none" stroke="#888888" stroke-width="2" />
</svg>

您首先将XML加载为文档:

You first load the XML as a Document:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse("image.svg");

然后使用XPath选择所需的节点.下面的表达式选择文件中所有path元素的d属性的内容:

Then you use XPath to select the desired nodes. The expression below selects the contents of the d attributes of all the path elements inside the file:

String xpathExpression = "//path/@d";

现在,我们可以实例化XPath处理器并编译表达式:

Now we can instantiate the XPath processor and compile the expression:

XPathFactory xpf = XPathFactory.newInstance();
XPath xpath = xpf.newXPath();
XPathExpression expression = xpath.compile(xpathExpression);

由于预期结果是一个节点集(两个字符串),因此我们使用XPathConstants.NODESET作为第二个参数来评估SVG文档上的表达式:

Since the expected result is a node-set (two strings), we evaluate the expression on the SVG document using XPathConstants.NODESET as the second parameter:

NodeList svgPaths = (NodeList)expression.evaluate(document, XPathConstants.NODESET);

您可以从此处使用以下命令提取第一组路径数据:

From there you can extract the first set of path data using:

svgPaths.item(0).getNodeValue();

这篇关于用Java读取svg路径数据的最简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆