How to connect to webcam in Java? - java

I have a form in which i want to capture the image of the person and display that image in the form.
How can i connect to the webcam through java and display that image in the form?

You could use JavaCV to capture the image.
This code should get you started (taken from here):
import com.googlecode.javacv.CanvasFrame;
import com.googlecode.javacv.FrameGrabber;
import com.googlecode.javacv.VideoInputFrameGrabber;
import com.googlecode.javacv.cpp.opencv_core.IplImage;
public class GrabberShow implements Runnable {
//final int INTERVAL=1000;///you may use interval
IplImage image;
CanvasFrame canvas = new CanvasFrame("Web Cam");
public GrabberShow() {
canvas.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
}
#Override
public void run() {
FrameGrabber grabber = new VideoInputFrameGrabber(0);
int i=0;
try {
grabber.start();
IplImage img;
while (true) {
img = grabber.grab();
if (img != null) {
cvFlip(img, img, 1);// l-r = 90_degrees_steps_anti_clockwise
cvSaveImage((i++)+"-capture.jpg", img);
// show image on window
canvas.showImage(img);
}
//Thread.sleep(INTERVAL);
}
} catch (Exception e) {
}
}
}
Another alternative would be to use the Java Media Framework (JMF). You can find an example here.

You can use Webcam Capture project to do that. It's working on Windows XP, Vista, 7, Linux, Mac OS, Raspberry Pi and more. There is a ready-to-use Swing component extending JPanel which can be used to display image from your webcam. Please found this example for more details of how this can be done - it presents some advanced capabilities of this component, but basic usage would be the following:
JFrame window = new JFrame("Test webcam panel");
window.add(new WebcamPanel(Webcam.getDefault()));
window.pack();
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
After you run this code you should see JFrame with image from your webcam inside.

Webcam.setAutoOpenMode(true);
BufferedImage image = Webcam.getDefault().getImage();
ImageIO.write(image, "PNG", new File("F:/test.png"));
can download the latest version from https://github.com/sarxos/webcam-capture
and add other library file that in the zip file

Related

Java - Maximizing window with Synthetica Look and Feel (LAF) and multiple monitors

I am using the Synthetica Black Eye LAF (http://www.jyloo.com/synthetica/) with an application using Java 1.7. It seems that when I have the Synthetica LAF enabled, if I drag the screen onto a second monitor that is larger, and I maximize the window by either double clicking or clicking on the maximize icon, the window takes up the same amount of space as the "Full screen" size on the primary monitor. When I do not have the LAF enabled it does not do this. it is as though it does not realize the dimensions of which screen it is on. Is there any workaround for this?
I have effectively done this:
Java Toolkit Getting Second screen size
and
java & fullscreen over multiple monitors
which is nice since now I can set the preferred size to that of the larger monitor, but that doesn't help me with my maximizing problem.
Here is my code:
package mil.innovation.bewear.maintenance.windows;
import de.javasoft.plaf.synthetica.SyntheticaBlackEyeLookAndFeel;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class Windows {
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(new SyntheticaBlackEyeLookAndFeel());
} catch (Exception e) {
System.out.println("Look and feel not started");
}
Dimension dimension;
GraphicsEnvironment graphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] devices = graphicsEnvironment.getScreenDevices();
GraphicsDevice biggest;
if (devices.length > 1) {
biggest = devices[0];
for (GraphicsDevice device : devices) {
if (device.getDefaultConfiguration().getBounds().getSize().getWidth() > biggest.getDefaultConfiguration().getBounds().getSize().getWidth())
biggest = device;
}
dimension = biggest.getDefaultConfiguration().getBounds().getSize();
} else if (devices.length == 1)
dimension = devices[0].getDefaultConfiguration().getBounds().getSize();
else {
throw new RuntimeException("No Screens detected");
}
String filePath = "C:\\Users\\Bewear2\\IdeaProjects\\bewear_windows\\imgNotFound.png";
JFrame frame = new JFrame("Example");
JLabel lblPicture = new JLabel();
lblPicture.setPreferredSize(dimension);
lblPicture.setSize(dimension);
BufferedImage image;
try {
image = ImageIO.read(new File("imgNotFound.png"));
lblPicture.setIcon(new ImageIcon(image));
}catch (IOException ex) {
System.out.println("Error loading the picture that is supposed to load when loading a picture fails" + ex);
}
try {
image = ImageIO.read(new File(filePath));
Image bufferedImg = image.getScaledInstance(lblPicture.getWidth(), lblPicture.getHeight(), Image.SCALE_SMOOTH);
lblPicture.setIcon(new ImageIcon(bufferedImg));
} catch (IOException ex) {
System.out.println("Error loading picture " + ex);
}
frame.setContentPane(lblPicture);
frame.pack();
frame.setVisible(true);
}
}
Email from customer support:
this is mainly a known Java Swing issue in multiscreen environments which occurs only when different screen resolutions will be used - see http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6829250. It's targeted to be fixed in V9. However, there was also another issue (#7010721 http://bugs.java.com/bugdatabase/view_bug.do?bug_id=7010721 ) which affects the window size so please make sure that a recent JVM will be used. If the issue still occurs a possible workaround is to enable the native frame decoration (see FAQ Window Decoration #1 http://www.jyloo.com/synthetica/faq/#windowDecoration-1 ) another workaround is to set the system property "synthetica.frame.fullscreen" to true, but this will cover the taskbar of the OS.

OpenCV not working correctly on mac

I have a program that uses OpenCV to take a picture using your webcam. It works like a charm on windows, yet, it doesn't work on OSx. The Frame where the Webcam view should appear stays empty. And when I take a picture, it just shows a black void, as if it couldnt find the webcam
public void run(){
try {
grabber = new VideoInputFrameGrabber(0);
grabber.start();
while (active) {
IplImage originalImage = grabber.grab();
Label.setIcon(new ImageIcon( originalImage.getBufferedImage() ));
}
grabber.stop();
grabber.flush();
} catch (Exception ex) {
//Logger.getLogger(ChPanel.class.getName()).log(Leve l.SEVERE, null, ex);
}
}
public BufferedImage saveImage(){
IplImage img;
try {
//capture image
img = grabber.grab();
// save to file
File outputfile = new File(Project.getInstance().getFileURLStr() + " capture" + fotoCount++ + ".jpg");
ImageIO.write(img.getBufferedImage(), "jpg", outputfile);
//get file and set it in the project library
BufferedImage ImportFile = ImageIO.read(outputfile);
Project p = Project.getInstance();
MainScreen ms = MainScreen.getInstance();
ImageIcon takenPhoto = new ImageIcon(ImportFile);
p.setNextImage(takenPhoto);
ms.setPanels();
return ImportFile;
} catch (com.googlecode.javacv.FrameGrabber.Exception e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Does anyone know how to solve this? I suspect something about rights to use the webcam or something like that
grabber = new VideoInputFrameGrabber(0);
Here 0 is specified for Capture device number 0
May be the number 0th device is not available for video capture
Use this code to get the list of devices and number respectively.
import com.googlecode.javacv.cpp.videoInputLib.videoInput;
class Main {
public static void main(String[] args) {
int n=videoInput.listDevices();
for(int i=0;i<n;i++)
{
System.out.println(i+" = "+videoInput.getDeviceName(i));
}
}
}
And then specify the number for that device
grabber = new VideoInputFrameGrabber(1); // 0 or 1 or 2
To interact with webcam I use this library webcam-capture you can easely add openCV dependency with maven. This is a great library

Can't define a path to an image

I imported an image into Eclipse, in the same package as this class:
public class mainWindow extends JFrame {
public mainWindow() {
Image bg = // \mainPackage\ShittyPlane.png;
Graphics2D g2d;
this.setSize(500,500);
this.setResizable(false);
this.setTitle("GameTest");
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
g2d.drawImage(bg, 0, 0, null);
}
}
How do I define the image path?
If the image is part of you source and is packed into jar later for distribution i would sucgest you get a stream to the image using getResourceAsStream.
ClassLoader cl = getClass().getClassLoader();
InputStream is = cl.getResourceAsStream("mainPackage/ShittyPlane.png");
BufferedImage image = ImageIO.read(is);
this aproache will also work in if you run the program from your IDE
If you plan to locate the image using a a File chooser then go with #Pescis's answer.
What you need to do to load an image from a specific file is:
BufferedImage img = null;
try {
img = ImageIO.read(new File("src/mainPackage/ShittyPlane.png")); //I'm guessing this is the path to your image..
} catch (IOException e) {
}
For more info you can read the javadoc on working with images.

ImageIcon not rendering for animation

I have tried to look at other topics with similar question like mine, and most of those solutions appear to point to fixing the classpath for images... so, I tried those by changing the classpath to absolute and using class get resource, but it still won't render the images. I have a suspicion that it has to do with the main method. I don't completely understand how that method works since I copied the source code somewhere online. I am using the Eclipse editor, and I already had put the image files alongside the Flap class file.
package wing;
import java.awt.*;
import javax.swing.*;
public class Flap extends JComponent implements Runnable {
Image[] images = new Image[2];
int frame = 0;
public void paint(Graphics g) {
Image image = images[frame];
if (image != null) {
// Draw the current image
int x = 0;
int y = 0;
g.drawImage(image, x, y, this);
}
}
public void run() {
// Load the array of images
images[0] = new ImageIcon(this.getClass().getResource("/Wing/src/wing/wing1.png"));
images[1] = new ImageIcon(this.getClass().getResource("/Wing/src/wing/wing2.png"));
// Display each image for 1 second
int delay = 10000; // 1 second
try {
while (true) {
// Move to the next image
frame = (frame+1)%images.length;
// Causes the paint() method to be called
repaint();
// Wait
Thread.sleep(delay);
}
} catch (Exception e) {
}
}
public static void main(String[] args) {
Flap app = new Flap();
// Display the animation in a frame
JFrame frame = new JFrame();
frame.getContentPane().add(app);
frame.setSize(800, 700);
frame.setVisible(true);
(new Thread(app)).start();
}
}
ImageIcon is not an Image :
images[0] = new ImageIcon(this.getClass().getResource("/Wing/src/wing/wing1.png")).getImage();
The application never ends, in main :
frame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
if isn't there any another JComponent(s) added to the public class Flap extends JComponent implements Runnable {
put Image as Icon to the JLabel
use Swing Timer instead of Runnable#Thread (required basic knowledge about Java and Threads too)
if there is/are another JComponent(s) added to the public class Flap extends JComponent implements Runnable {
don't use paint() use paintComponent() for Swing JComponents
use Swing Timer instead of Runnable#Thread (required basic knowledge about Java and Threads too)
in both cases load image as local variable, don't reload images forever
in both cases you have invoke Swing GUI from InitialThread
The resource name "/Wing/src/wing/wing1.png" looks suspicious: it means to locate a resource in the "/Wing/src/wing/" directory, which is most likely not where the resource actually is. Try "/wing/wing1.png" (similarly for the others)
The reason is that the src folder contains the source, which will be converted to classes. So "src/wing/Flap.java" will have the class path "/wing/Flap.class"; similarly for resources (depending on how you are packaging them).
Also, make sure the resource is indeed where you expect it to be (e.g. next to the Flap.class file in the output directory), otherwise the class loader will not find it.

Hows to open an .bmp/.jpeg image using Java

I am working on a JFrame/panel that will contain a button. When the user clicks the button, I want an image (which will be stored in the computer hard disk beforehand) to open on the front screen.
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//here i want a code that will somehow open the image from a given directory
}});
Any suggestions on how to go about this ? I have to tell where the image is stored and trigger a virtual 'double click' for the image to pop up on the front screen. Is that even possible using java to synchronize such computer functions?
I don't know a very short way, but I would use something like this (as qick hack to get an impression):
try {
// this is a new frame, where the picture should be shown
final JFrame showPictureFrame = new JFrame("Title");
// we will put the picture into this label
JLabel pictureLabel = new JLabel();
/* The following will read the image */
// you should get your picture-path in another way. e.g. with a JFileChooser
String path = "C:\\Users\\Public\\Pictures\\Sample Pictures\\Koala.jpg";
URL url = new File(path).toURI().toURL();
BufferedImage img = ImageIO.read(url);
/* until here */
// add the image as ImageIcon to the label
pictureLabel.setIcon(new ImageIcon(img));
// add the label to the frame
showPictureFrame.add(pictureLabel);
// pack everything (does many stuff. e.g. resizes the frame to fit the image)
showPictureFrame.pack();
//this is how you should open a new Frame or Dialog, but only using showPictureFrame.setVisible(true); would also work.
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
showPictureFrame.setVisible(true);
}
});
} catch (IOException ex) {
System.err.println("Some IOException accured (did you set the right path?): ");
System.err.println(ex.getMessage());
}
I think this will work ...
Code:
process = new ProcessBuilder("mspaint","yourFileName.jpeg").start();
This will open your image file with mspaint.....
and also use *Java Advanced Imaging (JAI)*
Try this code
try
{
// the line that reads the image file
BufferedImage image;
// work with the image here ...
image = ImageIO.read(new File("C://Users//Neo//Desktop//arduino.jpg"));
jLabel1.setIcon(new ImageIcon(image));
}
catch (IOException e)
{
// log the exception
// re-throw if desired
}
I'm not sure but try this...
try
{
JLabel picture=new JLabel();
ImageIcon ic=new ImageIcon(Toolkit.getDefaultToolkit().getImage(getClass().getResource("C:\\Users\\Desktop\\xyz.jpg")));
picture.setIcon(ic);
}
catch(Exception)
{
}

Categories

Resources