代码之家  ›  专栏  ›  技术社区  ›  Daniel Honig

如何从Java中的image Magick之类的程序中读取图像数据?

  •  0
  • Daniel Honig  · 技术社区  · 17 年前

    我可以这样调用命令到流程: /opt/local/bin/convert-调整8000@--

    从这样的进程中读取数据的最佳方式是什么?

    4 回复  |  直到 17 年前
        1
  •  2
  •   Mark Davidson    17 年前

    你可能想看看 Apache Commons Exec 这为您提供了一种运行可执行文件并将结果传递到Java的好方法。

    网上有一些很好的用法示例 tutorial

        2
  •  2
  •   Daniel Honig    17 年前

        try {
    
            StringBuffer sb = new StringBuffer();
            sb.append(this.validPathToImageMagickCommand);
            sb.append('\u0020');
            for (int i = 0; i < args.size(); i++) {
                String s = args.get(i);
                sb.append(s);
            }
    
    
            CommandLine cl = CommandLine.parse(sb.toString());
    
            PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(output, System.err, new ByteArrayInputStream(inputBytes));
            byAs = new ByteArrayInputStream(inputBytes);
            pumpStreamHandler.setProcessOutputStream(byAs);
    
            DefaultExecutor executor = new DefaultExecutor();
            executor.setStreamHandler(pumpStreamHandler);
            int exitValue = executor.execute(cl);
    
            outputBytes = output.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (byAs != null)
                    byAs.close();
    
                if (output != null)
                    output.close();
    
            } catch (IOException e) {
                System.out.println(e);
            }
    
        }
    
        3
  •  1
  •   Michael Borgwardt    17 年前

    这个 Runtime.exec() 方法返回一个 Process

    请注意,您必须使用多个线程来处理生成的进程的输入和输出,因为如果您尝试在不读取任何输出的情况下“导入”大量输入,它将阻塞。

        4
  •  1
  •   Community Mohan Dere    9 年前

    如果确实要使用Runtime.exec(),请查看 this question 例如runtime.exec()可能有点棘手。

    您可能希望将输出的StreamGobbler更改为将stdout存储在数组中或类似的东西。并在执行waitFor()之前启动线程,以防止如Michael所说的阻塞。