简体   繁体   中英

Run Bash from Java Program to Capture Webcam Image on Raspberry Pi

On my Raspberry Pi, I can successfully capture and save images from my Logitech Pro 9000 USB webcam from LXTerminal with the following bash line:

fswebcam -d /dev/video0 /home/pi/image.jpg

I want to write a java program that runs the bash line above because it is the simplest way to capture and save an image. So far, I have:

import java.io.*;

public class GrabNSave {
  public static void main(String[] args) throws IOException {
  Runtime.getRuntime().exec("/bin/bash -c fswebcam -d /dev/video0 /home/pi/image.jpg");
  }
}

It's not working. I get no error messages. Please help!

First, you need to install fswebcam ....

sudo apt-get install fswebcam

Then, in your Java program, you need to run the following :

Runtime.getRuntime().exec("fswebcam -d /dev/video0 /home/username/Desktop/test.jpg");

Worked for me, hopefully it does for you! =)

I had this same problem at first, by the way.. =)

Good luck!

/bin/bash -c fswebcam -d /dev/video0 /home/pi/image.jpg will not work in bash either, you need to add quotes so that bash receives the command as a single argument:

 /bin/bash -c 'fswebcam -d /dev/video0 /home/pi/image.jpg'

But I'd recommand using a simpler version:

 Runtime.getRuntime().exec("fswebcam -d /dev/video0 /home/pi/image.jpg")

or if you need to change the arguments something among the lines of:

 String[] command = {"fswebcam", "-d", "/dev/video0", "/home/pi/image.jpg"}
 Runtime.getRuntime().exec(command)

If you handle the InputStream you get from the Process it should work: `

            Process process = Runtime.getRuntime().exec("sudo fswebcam -r 320x240 -d /dev/video0 /home/pi/apache-tomcat-7.0.37/webapps/co/cam1.jpg");
            InputStream ips = process.getErrorStream();

            int b = 0;
            while ((b = ips.read()) > 0) {
                // do something 
            }

`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM