使用Java从XML文件创建图形图像(png,jpg ..) [英] Create a graph image (png, jpg ..) from an XML file with Java

查看:554
本文介绍了使用Java从XML文件创建图形图像(png,jpg ..)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个XML文件,我想用一些实体创建一个图形,然后将此图形存储在JPG或PNG图片中.

I have an XML file and I want to create a graph with some entities, then store this graph in an image, JPG or PNG.

那么Java是否有一个像这样的库?还是通过解析XML文件和一些技巧?...

So is there a library in Java do like this?? Or is there some tricks by parsing XML files and ... ???

这里是一个例子 XML文件:

Here an example XML file:

<?xml version="1.0"?>
<process>
  <p n="1">Tove</p> 
  <p n="2">Jani</p> 
  <p n="2">Bill</p> 
  <p n="4">John</p> 
</process>

输出将是这样的:

推荐答案

您可以使用多种Java XML库之一提取名称.这是一个 Java DOM 中使用XPath的示例:

You can extract the names using one of the myriad of Java XML libraries. Here's an example using XPath from a Java DOM:

private static List<String> findNames(Document doc)
                                           throws XPathExpressionException {
  XPath xpath = XPathFactory.newInstance().newXPath();
  NodeList nodes = (NodeList) xpath.evaluate("/process/p", doc, 
                                                    XPathConstants.NODESET);
  List<String> names = new ArrayList<String>();
  for (int i = 0; i < nodes.getLength(); i++) {
    names.add(nodes.item(i).getTextContent());
  }
  return names;
}

注意:这可能是拼写错误,但是您的XML格式不正确-必须用引号将属性值引起来.否则XML解析将失败.

您可以使用 AWT API 绘制您想要的任何东西:

You can use the AWT API to draw whatever you want:

private static final int BORDER = 1;
private static final int PADDING = 2;
private static final int SPACER = 5;

private static void draw(Graphics2D g, List<String> names) {
  FontMetrics metrics = g.getFontMetrics();
  Rectangle box = new Rectangle(1, 1, 0, 0);
  box.height = metrics.getHeight() + (PADDING * 2);
  g.setColor(Color.WHITE);
  for (String name : names) {
    box.width = metrics.stringWidth(name) + (PADDING * 2);
    g.drawString(name, box.x + BORDER + PADDING, PADDING + BORDER +
                                                    metrics.getHeight());
    g.drawRect(box.x, box.y, box.width, box.height);
    box.x += box.width + (BORDER * 2) + SPACER;
  }
}

此代码仅在名称周围带有一些框的位置绘制.我确信我的补偿措施到处都是,但您可能会明白.

This code just draws the names with some boxes around them. I'm sure my offsets are all over the place, but you probably get the idea.

有一个 imageio API 可以保存为几种流行的数据格式:

There is an imageio API that can save in a few popular data formats:

private static void save(List<String> names, File file) throws IOException {
  BufferedImage image = new BufferedImage(600, 50, BufferedImage.TYPE_INT_RGB);
  Graphics2D g = image.createGraphics();
  try {
    draw(g, names);
  } finally {
    g.dispose();
  }
  ImageIO.write(image, "png", file);
}

这篇关于使用Java从XML文件创建图形图像(png,jpg ..)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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