2

I'm trying to run a simple image-capture script using PhantomJS from within my Java program. The end goal is to automate the process of taking screenshots of specific webpages.

My problem is that when I run the following code, the program exits with a return value of -1 and no image is produced:

Process process = new ProcessBuilder("C:\\PhantomJS\\phantomjs.exe", "imagecap.js", "http://www.google.com", "google.png").start();
process.waitFor();
System.out.println("Program exited with: " + process.exitValue());

However, when I run the equivalent command from the windows command prompt:

C:\PhantomJS\phantomjs.exe imagecap.js http://www.google.com google.png

It runs fine and produces the correct .png file.


I've also tried having Java run the command through cmd.exe as Administrator with no luck:

Process process = Runtime.getRuntime().exec("runas /profile /user:Administrator \"cmd /c start /wait" +
    "C:\\PhantomJS\\phantomjs.exe imagecap.js http://www.google.com google.png\"");

The above code returns 1 instead of -1 like the first example, although I have no idea why.


The tiny Javascript script I'm running through PhantomJS is:

var page = require('webpage').create();
page.viewportSize = { width: 1600, height: 1024 };
var system = require('system');

page.open(system.args[1], function() {  
    page.render(system.args[2])
    phantom.exit();
});

I absolutely know the script works, I can run it manually and it works flawlessly.

I'd like to know if anyone can explain to me why my attempts to run this using Java are failing.

Christopher Sheaf
  • 185
  • 1
  • 3
  • 13
  • Have you tried logging standard error and standard output of the `Process`? – Elliott Frisch Feb 03 '14 at 01:13
  • @Elliot Frisch, Nothing is being sent to either of those as far as I can tell. – Christopher Sheaf Feb 03 '14 at 01:20
  • 2
    Does the java program have a different current directory? Maybe `phantomjs` is having trouble writing to the current directory when it's run from java. – Kenster Feb 03 '14 at 01:58
  • @Kenster That worked. I'm flabbergasted that it worked, but somehow moving my program to the same directory as `phantomjs` made it work.The part that confuses me is that `phantomjs` was writing to its _own_ directory, not the directory my program was located in. Why would `phantomjs` be unable to write to its own directory unless my program was also in the same directory? It didn't previously function when I gave an absolute path for the image file, either. – Christopher Sheaf Feb 03 '14 at 02:22

0 Answers0