Infolinks In Text Ads

May 4, 2011

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;
}

5 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

Related Posts Plugin for WordPress, Blogger...