如何使用Graphviz从点文件格式生成PNG图像

6
我有一个实现优先队列的Java类。然后我有一个测试类,生成了这样一个图形:
digraph G {
Milan  (0.0)       ->     Turin  (1.2)       
Milan  (0.0)       ->     Montreal  (7.0)       
Turin  (1.2)       ->     Paris  (5.8)       
Turin  (1.2)       ->     Tokyo  (2.2)       
}

这张图被保存在一个名为“queue”的文件中。现在我希望使用Graphviz将这张图显示为PNG格式的图片。因此,在您创建并填充了优先队列之后,我的测试文件的最后一次调用是:
queue.toString("queue");

好的。toString方法如下:

toString方法的作用是将对象转换为字符串形式。

public void toString(String fileDot){
    try {
        FileOutputStream file = new FileOutputStream(fileDot); 
        PrintStream Output = new PrintStream(file); 
        Output.print(this.printQueue()); 
        Output.close(); 
        File f = new File(fileDot); 
        String arg1 = f.getAbsolutePath(); 
        String arg2 = arg1 + ".png"; 
        String[] c = {"dot", "-Tpng", arg1, "-o", arg2};
        Process p = Runtime.getRuntime().exec(c); 
        int err = p.waitFor(); 
    }
    catch(IOException e1) {
        System.out.println(e1);
    }
    catch(InterruptedException e2) {
        System.out.println(e2);
    }
}

private String printQueue() throws IOException {
    String g = new String("");
    char c = '"';
    g = g.concat("digraph G {\n");
    if(isEmpty()) 
        g = g.concat("    " + "Empty priority queue.");
    else {
        for(int i = 0; i < lastIndex; i++) {
            if(heap[2 * i] != null) { 
                g = g.concat("" + heap[i].elem + "  (" + heap[i].prior + ")   " + "   " + " -> " + "    " + "" + heap[i * 2].elem + "  (" + heap[i * 2].prior + ")       \n" );
                if(heap[2 * i + 1] != null) 
                    g = g.concat("" + heap[i].elem + "  (" + heap[i].prior + ")   " + "   " + " -> " + "    " + "" + heap[i * 2 + 1].elem + "  (" + heap[i * 2 + 1].prior + ")       \n" ); 
            } 
        } //end for
    } //end else  
    g = g.concat("}");
    return g;   
}

为什么生成不了.png格式的图片?我做错了什么吗?当然,我已经安装了Graphviz。谢谢。
2个回答

16

当我在命令行上运行上述的.dot文件并使用dot进行处理时,我得到了以下结果:

$ dot -Tpng queue.dot -oqueue.png
Warning: queue.dot:2: syntax error in line 2 near '('

因此,节点名称中括号内的数字在dot语法中无效。如果您删除它们,我预计.png文件将成功创建。如果您需要在输出中使用括号内的数字,请查阅GraphViz文档中的节点标签。

我还要指出,toString()不像是一个特别清晰的函数名称,用于创建一个.png文件,因此更改函数名称可能是明智的。


非常感谢!标签的格式不正确。再次感谢您。 - user3425699

1

尝试使用dot-O选项,而不是-o。根据dot -?的说明,它的作用如下:

  • 自动基于输入文件名生成一个带有“格式”后缀的输出文件名。(导致所有的-ofile选项被忽略。)

因此,您可以更改

String[] c = {"dot", "-Tpng", arg1, "-o", arg2};

to

String[] c = {"dot", "-Tpng", arg1, "-O"};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接