imagemagick Convert 在命令行中工作但不在 java 进程运行时中工作

imagemagick Convert working in Command line but not in java process runtime

我有一个 tif 图像,我试图在其中绘制一个框并同时使用 LZW 压缩来压缩图像。

这是我 运行 的命令,它在 windows 命令行下工作正常。

C:\ImageMagick-7.1.0\convert.exe "C:\Users\admin\Orig.tif" -draw "rectangle 576,1069,943,1114" -compress LZW "C:\Users\admin\DrawLZW.tif"

当我尝试用我的 java 程序执行相同的命令时,我创建了一个图像文件,但文件大小为 1kb

        String[] cmd = {"C:\ImageMagick-7.1.0\convert.exe", "\"C:\Users\chris.macwilliams\Orig.tif\"", "-draw", "\"rectangle 576,1069,943,1114\"", "–compress","LZW", "\"C:\Users\chris.macwilliams\DrawLZWwithJava.tif\""};
        LOGGER.info(cmd);
        Process pt = Runtime.getRuntime().exec(cmd);
        pt.waitFor();

        if (pt.exitValue() != 0) {
            LOGGER.error("ERROR with Image Magic Command exit value:" + pt.exitValue()+  " "+ commandTIF);

有什么想法吗?

使用IM版本:ImageMagick-7.1.0 我已经包含了出现错误的测试图像。 zip file download

如果您使用的是数组,在执行 cmd 之前声明数组的大小并添加每个参数会更容易。

private void redactCMDArray() {
    String[] cmd = new String[7];
    cmd[0] = "C:\ImageMagick-7.1.0\convert.exe";
    cmd[1] = "\"C:\Users\Administrator\Desktop\images\Orig.tif\"";
    cmd[2] = "-draw";
    cmd[3] = "rectangle 576,1069,943,1114";
    cmd[4] = "-compress";
    cmd[5] = "LZW";
    cmd[6] = "\"C:\Users\Administrator\Desktop\images\DrawLZW_CMD_Option1.tif\"";
    System.out.println(Arrays.toString(cmd));
    Process pt;
    try {
        pt = Runtime.getRuntime().exec(cmd);
        pt.waitFor();
        if (pt.exitValue() != 0) System.out.println("ERROR with Image Magic Command exit value:" + pt.exitValue()+  " " + Arrays.toString(cmd));
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
    }
}

如 Esther 所述,另一种选择是在命令中的参数之间添加一个空格而不传递数组。

private void redactCMDLine(){
    String imPath = "C:\ImageMagick-7.1.0\convert.exe";
    String imEXE = "/convert.exe";

    String cmd = imPath + imEXE + " " + "C:\Users\Administrator\Desktop\images\Orig.tif" + " " + "-draw \"rectangle 576,1069,943,1114\"" + " " + "-compress LZW"  + " " + "C:\Users\Administrator\Desktop\images\DrawLZW_CMD_Option2.tif";
    try {
        Process p = Runtime.getRuntime().exec(cmd);
        p.waitFor();
        System.out.println("Exit code: " + p.exitValue());
    } catch (InterruptedException | IOException e) {
        e.printStackTrace();
    }
}

如果 IM4Java jar 可用,更直接的解决方案如下。

private void redactIM4Java() {
    ConvertCmd convertCmd = new ConvertCmd();
    IMOperation op = new IMOperation();
    op.addImage("C:\Users\Administrator\Desktop\images\Orig.tif");
    op.fill("Black");
    op.draw("rectangle 576,1069,943,1114");
    op.compress("LZW");
    op.format("TIF");
    op.addImage("C:\Users\Administrator\Desktop\images\DrawLZW_MB_JavaIM4Java.tif");
    try {
        convertCmd.run(op);
    } catch (IOException | InterruptedException | IM4JavaException e) {
        e.printStackTrace();
    }
}