Search code examples
javajmf

Taking Snapshots from a Webcam using JMF


I want to take a snapshot from a webcam through java. I followed this question and arrived at the this example. But there is a null pointer exception coming from the below line -

Buffer buf = frameGrabber.grabFrame();
Image img = (new BufferToImage((VideoFormat) buf.getFormat())
                .createImage(buf));
        buffImg = new BufferedImage(img.getWidth(this), img.getHeight(this),
                BufferedImage.TYPE_INT_RGB);

Through the debugger I observed that the buffer doesn't actually contain data. So I went the creation of frameGrabber.

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

Is there a problem with this code. Because JMFStudio works fine in my machine but the code cannot access it. Thank you.


Solution

  • I found the solution. The JMF needs time for initialization. In the example we have to switch a line. Put the

    new Timer(3000, this).start();
    

    below the try catch.

    The whole block looks like below.

            try {
                player = Manager.createRealizedPlayer(cdi.getLocator());
                player.start();
            } catch (NoPlayerException e) {
                e.printStackTrace();
            } catch (CannotRealizeException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
                new Timer(3000, this).start();
            // Grab a frame from the capture device
            frameGrabber = (FrameGrabbingControl) player
                    .getControl("javax.media.control.FrameGrabbingControl");