Java Web Cam Example using JMF

After long time i have decide to post again about Java web cam which I have  explained before .

Last time i have used video4linux with linux platform but this time I’m going to use Java Media Framework (JMF) with with windows platform.

First you have to instal the JMF into windows you can download it from Oracle website.Next you have to import JMF plugins into your project .

In here I have used netbeans IDE there for you can see some methods which are not useful for jmf but IDE has includes for its source code by itself.

ex

In hare i have created JFrame and load jmf components into JPanel .

Code Example :

This is the code should be in your jframe in here i have not include the codes regarding for creating of jframe.

public class SimpleWebCam extends javax.swing.JFrame {

    CaptureDeviceInfo device;
    MediaLocator ml;
    Player player;
    Component videoScreen;

    public SimpleWebCam() {
        initComponents();
        // path to webcam in windows web cam device is located in here
        String mediaFile = "vfw:Micrsoft WDM Image Capture (Win32):0";

            ml = new MediaLocator(mediaFile);
        try {
            player = Manager.createRealizedPlayer(ml);

            player.start();
            // create video screen to display webcam preview
            videoScreen = player.getVisualComponent();
            videoScreen.setSize(p1.getSize());
            p1.removeAll();
            p1.add(videoScreen, BorderLayout.CENTER);
            p1.repaint();
            p1.revalidate();

            p2.removeAll();
            p2.add(player.getControlPanelComponent());
            p2.repaint();
            p2.revalidate();

        } catch (IOException ex) {
            Logger.getLogger(SimpleWebCam.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoPlayerException ex) {
            Logger.getLogger(SimpleWebCam.class.getName()).log(Level.SEVERE, null, ex);
        } catch (CannotRealizeException ex) {
            Logger.getLogger(SimpleWebCam.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

This is the code part which is should be in your ” Capture ” Button event .


private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        try {

            Thread.sleep(100);//wait 10 seconds before capturing photo
        } catch (InterruptedException ex) {
            Logger.getLogger(SimpleWebCam.class.getName()).log(Level.SEVERE, null, ex);
        }

            FrameGrabbingControl fgc = (FrameGrabbingControl) player.getControl("javax.media.control.FrameGrabbingControl");

            Buffer buf = fgc.grabFrame();//grab the current frame on video screen

            BufferToImage btoi = new BufferToImage((VideoFormat) buf.getFormat());

            Image img = btoi.createImage(buf);
            // save image to file
             saveImagetoFile(img, "MyPhoto.jpg");

             new campic(img).setVisible(true);
    }

Method for save captured image in the hard disk (this method calls inside the capture button action performed event )

 private void saveImagetoFile(Image img, String string) {

            int w = img.getWidth(null);
            int h = img.getHeight(null);
            BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = bi.createGraphics();

            g2.drawImage(img, 0, 0, null);

            g2.dispose();

            String fileType = string.substring(string.indexOf('.') + 1);
        try {
            ImageIO.write(bi, fileType, new File(string));
        } catch (IOException ex) {
            Logger.getLogger(SimpleWebCam.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

I hope you will understand the example you can download complete project file from here
Download Project

Webcam example using Video4Linux – How to capture image using webcam in java

Today i am going to tell you how to developed simple Webcam application for linux using java. If you are using windows you can easily develop using Java Media Framework (JMF). But JMF is not support for Linux there for we have to use external library call Video4Linux4Java (v4l4j).

First of all you have to install v4l4j or else you have to import v4vl4j.jar file to your project .You can get all the instructions to set up v4l4j from the video for linux website.

This is a sample code for accessing webcam , capture image and save it .

Simple Webcam App with capture button

Simple Webcam App with capture button

Saving image

Saving image

 


package MyCam;

import au.edu.jcu.v4l4j.*;
import au.edu.jcu.v4l4j.exceptions.StateException;
import au.edu.jcu.v4l4j.exceptions.V4L4JException;
import com.sun.java.swing.plaf.gtk.GTKLookAndFeel;
import java.awt.BorderLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.*;

/**
*
*
* @author madushanka
*
*/
public class MyCam extends WindowAdapter implements CaptureCallback {

private static int width = 640, height = 480, std = V4L4JConstants.STANDARD_WEBCAM, channel = 0;
private static String device = "/dev/video0"; //getting device this is the path of device
private VideoDevice videoDevice;
private FrameGrabber frameGrabber;
private JLabel label;
private JFrame frame;
private JButton button;
BufferedImage bf;

public static void main(String args[]) throws UnsupportedLookAndFeelException {

UIManager.setLookAndFeel(new GTKLookAndFeel());
new MyCam();

}

public MyCam() {


try {
initFrameGrabber();     // creating frame grabber
} catch (V4L4JException e1) {
System.err.println("Error setting up capture");
e1.printStackTrace();


cleanupCapture();
return;
}


initGUI(); // creating Jframe


try {
frameGrabber.startCapture();   // Starting cam
} catch (V4L4JException e) {
System.err.println("Error starting the capture");
e.printStackTrace();
}
}

private void initFrameGrabber() throws V4L4JException {   // Setting Framegrabber
videoDevice = new VideoDevice(device); // getting the webcam
frameGrabber = videoDevice.getJPEGFrameGrabber(width, height, channel, std, 80);
frameGrabber.setCaptureCallback(this);
width = frameGrabber.getWidth();
height = frameGrabber.getHeight();

}

private void initGUI() {    // setting JFrame
frame = new JFrame();
label = new JLabel();
button = new JButton("Capture");
frame.getContentPane().add(label);
frame.getContentPane().add(button, BorderLayout.PAGE_END);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.addWindowListener(this);
frame.setTitle("WebCam Example");
frame.setVisible(true);
frame.setSize(width, height);
button.addMouseListener(new MouseAdapter() {

public void mouseClicked(MouseEvent e) {

System.out.println(bf);
try {
ImageIO.write(bf, "png", new File("out.png"));    // saving image
JOptionPane.showMessageDialog(null, "Saved !!!");
} catch (IOException ex) {
Logger.getLogger(MyCam.class.getName()).log(Level.SEVERE, null, ex);
}


}
});
}

// this method is use for turn off cam and release framegrabber and device
private void cleanupCapture() {
try {
frameGrabber.stopCapture();
} catch (StateException ex) {
}


videoDevice.releaseFrameGrabber();
videoDevice.release();
}

@Override
public void exceptionReceived(V4L4JException e) {

e.printStackTrace();
}

// this method is call from startCapture() method
// getting the frame from framegrabber and draw it on JLable to show the user and recycle frame
// again getting frame , showing it , recycle it
@Override
public void nextFrame(VideoFrame frame) {
setImage(frame.getBufferedImage()); // get the captured frame to Buffered Image

label.getGraphics().drawImage(frame.getBufferedImage(), 0, 0, width, height, null);


frame.recycle();

}

public void setImage(BufferedImage b) {
bf = b;
}

public BufferedImage getImage() {
return bf;
}
}