Alex
Alex

Reputation: 35179

Calling imagemagick from java not working, direct call works

I am having the following java code to blur faces in images - the variable convert is set to /usr/bin/mogrify

//String []cmd = {convert, "-region", f.w+"x"+f.h+"+"+x+"+"+y, "-blur 0.0x10.0", path};

String cmd = convert + " -region " + f.w+"x"+f.h+"+"+x+"+"+y + " -blur 0.0x10.0 " + "\"" + path + "\"";

System.out.println(cmd);
// System.out.println(strJoin(cmd, " ")); 
Process p = Runtime.getRuntime().exec(cmd);
    BufferedReader in = new BufferedReader(  
                        new InputStreamReader(p.getInputStream()));  
    String line = null;  
    while ((line = in.readLine()) != null) {  
        System.out.println(line);  
    }  
p.waitFor();

But nothing happens on the images.

The program also outputs the command line it would call, for example:

/usr/bin/mogrify -region 37x44+1759+881 -blur 0.0x10.0 "/home/self/.wine/drive_c/windows/profiles/self/My Pictures/test/pic00164.jpg"

If I call this line manually, everything works fine.

As you can see from the comments, I also tried supplying cmd as an array which should automatically escape the spaces in my path - same effect: none.

Upvotes: 1

Views: 548

Answers (2)

Alex
Alex

Reputation: 35179

getErrorStream() - as mentioned in a comment - was the key to success. The escaping did not work the way I tried it. Then I tried it with an array and found our that I have to split up the blur option.

This works:

String []cmd = {convert, "-region", f.w+"x"+f.h+"+"+x+"+"+y, "-blur", "0.0x10.0", path};

Upvotes: 0

ursa
ursa

Reputation: 4611

Never build command line by hands - there is no single portable solution for this. It works only in rare cases, where no spaces or (double) quotes are present in the command line.

Use process builder instead:

ProcessBuilder pb = new ProcessBuilder(
    convert, "-region", f.w+"x"+f.h+"+"+x+"+"+y, "-blur 0.0x10.0", path);
pb.redirectError();
Process process = pb.start();
BufferedReader in = new BufferedReader(
    new InputStreamReader(process.getInputStream()));

Upvotes: 2

Related Questions