Selasa, 08 Mei 2012

How To Use WebCam Using Java

A While a go i need to make a java program that use webcam to capture image and then save it to harddrive. In this post i want to share how to use webcam using java. What in my mind when i want to make the java program that use webcam is Java Media Framework. But there is a simple way how to access webcam using java. The way is using library called JMyron. In JMyron library there is only 4 files :
1. JMyron.jar
2. JMyron.dll
3. DSVL.dll
4. myron_ezcam.dll

If we use Netbeans IDE. add JMyron.jar to the Libraries using Add Jar/Folder menu. And copy all dll files to the root directory of our Netbeans Project.

here the sampe code how to start using JMyron

private void configureMycron() {
        m = new JMyron();//make a new instance of the object
        m.start(width, height);//start a capture at 320x240       
        //m.findGlobs(0);//disable the intelligence to speed up frame rate
        m.findGlobs(0);
        //set labels
        lblCameraView.setBounds(new Rectangle(width, height));

    }

    private void getCameraImage() {
        captureImage = new BufferedImage(width, height, BufferedImage.OPAQUE);
        m.update();//update the camera view
        imageIntArray = m.image(); //get the normal image of the camera
        captureImage.setRGB(0, 0, width, height, imageIntArray, 0, width);
    }

    private void startCapture() {
        configureMycron();
        captureOn = true;
        Runnable capture = new Runnable() {

            public void run() {
                while (captureOn) {
                    try {
                        getCameraImage();
                        lblCameraView.setIcon(new ImageIcon(captureImage));                       
                        Thread.sleep(frameRate);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(SimpleTest.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        };
        Thread t = new Thread(capture);
        t.start();
        btnStartCapture.setEnabled(false);
    }

6 komentar: