Capture image from webcam java code, examples

import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.net.MalformedURLException;
import java.net.URL;

import javax.media.Buffer;
import javax.media.CaptureDeviceInfo;
import javax.media.CaptureDeviceManager;
import javax.media.Manager;
import javax.media.MediaLocator;
import javax.media.Player;
import javax.media.control.FrameGrabbingControl;
import javax.media.format.VideoFormat;
import javax.media.util.BufferToImage;
import javax.swing.JButton;
import javax.swing.JComponent;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class Camagain extends Applet implements ActionListener {

    /**
     *
     */
    private static final long serialVersionUID = -196359544994677518L;
    public static Player player;
    public CaptureDeviceInfo DI;
    public MediaLocator ML;
    public JButton CAPTURE;
    public Buffer BUF;
    public Image img;
    public VideoFormat VF;
    public BufferToImage BtoI;
    public ImagePanel imgpanel;
    public javax.swing.Timer timer = new javax.swing.Timer(200, this); // 200ms is too fast increase it to suit your need

    public void init(){
         purl = getParameter("url");
         url = purl;
        setLayout(new BorderLayout());
        setSize(320, 600);

        imgpanel = new ImagePanel();
        CAPTURE = new JButton("Capture");
        CAPTURE.addActionListener(this);

        String str1 = "vfw:Logitech USB Video Camera:0";
        String str2 = "vfw:Microsoft WDM Image Capture (Win32):0";
        DI = CaptureDeviceManager.getDevice(str2);
        ML = new MediaLocator("vfw://0");

        try {
            player = Manager.createRealizedPlayer(ML);
            player.start();
            Component comp;
            if ((comp = player.getVisualComponent()) != null) {
                add(comp, BorderLayout.NORTH);
            }
            add(CAPTURE, BorderLayout.CENTER);
            add(imgpanel, BorderLayout.SOUTH);
            Thread.sleep(5000);     // this is important, otherwise you may get NPE somewhere, needs polishing ;-)
            timer.start();                // start timer
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
   
    public void executeCapture(Camagain cf) {
        Frame f = new Frame("SwingCapture");
        //camagain cf = new camagain();   // I didn't had 'SwingCapture, so I added camgain.....

        f.addWindowListener(new WindowAdapter() {

            public void windowClosing(WindowEvent e) {
                playerclose();
                //System.exit(0);
            }
        });

        f.add("Center", cf);
        f.pack();
        f.setSize(new Dimension(320, 600));
        f.setVisible(true);
    }
    public static void playerclose() {
        player.close();
        player.deallocate();
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() instanceof JComponent) {
            JComponent c = (JComponent) e.getSource();
            if (c == CAPTURE) {
                actionCapture();  // maoved every thing to new method action()
            }
        } else if (e.getSource() instanceof javax.swing.Timer) {
            action();       // timer event , call action() again
        }
    }

    public void action() {    // your action handler code.....
        // Grab a frame
        FrameGrabbingControl fgc = (FrameGrabbingControl) player.getControl("javax.media.control.FrameGrabbingControl");
        BUF = fgc.grabFrame();

        // Convert it to an image
        BtoI = new BufferToImage((VideoFormat) BUF.getFormat());
        img = BtoI.createImage(BUF);

        // show the image
        //imgpanel.setImage(img);

        // save image
       /* String path = System.getProperty("user.home")+"/xtest.jpg";
        // save image
        saveJPG(img, path);*/

        //webImageShow(path)
        /*System.out.println("Before Alert----");
        try {
            getAppletContext().showDocument
              (new URL("javascript:webImageShow(\"" + path +"\")"));
            }
          catch (MalformedURLException me) { }
         
          System.out.println("After Alert----");*/
    }

    public void actionCapture() {    // your action handler code.....
        // Grab a frame
        FrameGrabbingControl fgc = (FrameGrabbingControl) player.getControl("javax.media.control.FrameGrabbingControl");
        BUF = fgc.grabFrame();

        // Convert it to an image
        BtoI = new BufferToImage((VideoFormat) BUF.getFormat());
        img = BtoI.createImage(BUF);

        // show the image
        imgpanel.setImage(img);

        // save image
       
        String fileName = System.currentTimeMillis()+".jpg";
       
        String path = System.getProperty("user.home")+"/"+fileName;
       
        // save image
        saveJPG(img, path);
        //upload(path, url);
       
        //Upload upload1 = new Upload(null, path, "http://10.10.0.176:8080/i-hrpro/upload_file.jsp");
        Upload upload1 = new Upload(null, path, url);
        (new Thread(upload1)).start();
       
        //webImageShow(path)
       
       //path = path.replace("\\", "/");
        //System.out.println("Before Alert----" + path);
        try {
            getAppletContext().showDocument
              (new URL("javascript:webImageShow(\"" + fileName +"\")"));
            }
          catch (MalformedURLException me) { }
         
          System.out.println("After Alert----");
    }
    class ImagePanel extends Panel {

        public Image myimg = null;

        public ImagePanel() {
            setLayout(null);
            setSize(320, 240);
        }

        public void setImage(Image img) {
            this.myimg = img;
            repaint();
        }

        public void paint(Graphics g) {
            super.paint(g);
            g.drawImage(myimg, 0, 0, this);
        }
    }

    public static void saveJPG(Image img, String s) {
        BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = bi.createGraphics();
        g2.drawImage(img, null, null);
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(s);
        } catch (java.io.FileNotFoundException io) {
            System.out.println("File Not Found");
        }

        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
        JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
        param.setQuality(0.5f, false);
        encoder.setJPEGEncodeParam(param);

        try {
            encoder.encode(bi);
            out.close();
        } catch (java.io.IOException io) {
            System.out.println("IOException");
        }
    }
   
    String url;
    String purl;
}

Comments

  1. Hi Manoj,am not getting any exception but image capture is not happening..

    ReplyDelete
  2. Thanks it worked......

    ReplyDelete
  3. Hi ,
    I have error of upload class i.e cannot find symbol
    Can plz rply me fast!!!!!!!!!!!!

    ReplyDelete
  4. Can u plz tell how to define Class Upload u have used.............it is giving an error.........

    ReplyDelete
  5. It is not working,, guys please,, if you put codes,, explain how to execute it,, which frameworks or libraries we should install or import

    ReplyDelete
  6. i have 28 errors...pls help me..i really need this program..its for our thesis projetc...we really need to apply this codes...pls response...im waiting...thanks...God Bless

    ReplyDelete
  7. This example is based on JMF which is outdated and not being maintained any more. For good Java library which will allow you to capture images from webcam and which is compatible with most existing operating systems, please take a look on https://github.com/sarxos/webcam-capture

    ReplyDelete
  8. Is there any external libraries need to be installed for this program?

    ReplyDelete
  9. I Really Like Your Post.Thanks For Sharing
    Online Knowledge Academy

    ReplyDelete
  10. This comment has been removed by the author.

    ReplyDelete
  11. I read that Post and got it fine and informative.
    adult chat

    ReplyDelete
  12. I really wana thank you for providing such informative and qualitative material so often.
    vibrators

    ReplyDelete
  13. Very efficiently written information. It will be beneficial to anybody who utilizes it, including me. Keep up the good work. For sure i will check out more posts. This site seems to get a good amount of visitors. live cam shows

    ReplyDelete
  14. Very efficiently written information. It will be beneficial to anybody who utilizes it, including me. Keep up the good work. For sure i will check out more posts. This site seems to get a good amount of visitors. live cam shows

    ReplyDelete
  15. This is my first time i visit here. I found so many interesting stuff in your blog especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the enjoyment here keep up the good work chaturbate

    ReplyDelete
  16. Positive site, where did u come up with the information on this posting? I'm pleased I discovered it though, ill be checking back soon to find out what additional posts you include. chaturbat

    ReplyDelete

Post a Comment

Recent Post

Recent Posts Widget

Popular posts from this blog

How to capture finger prints in java

Shallow Copy Deep Copy Java example