No Question, just example web cam capture code

Hi,
Since loads of people ask for an example of capturing pics from a web cam, here's one that captures pics, lets you take snapshots, which it displays in another frame. When you shut down the frame it asks if you want to save it to a JPEG.
I'm mainly posting this to spite Eka_Kupkova, who only visits this forum to shamelessly advertise a commercial Twain based package in every single posting on this forum which mentions web cams.
Notes : ( Could be more, read the install docs for JMF )
1. you must download the "performance" version of jmf to capture video.
2. I "think" you need to setup the JMF_HOME environment variable
3. Run the jmfinit program to detect your camera and register it.
I had to run it a couple of times before it worked.
4. I had 2 icons for my toolbar, BtnFormat.jpg and BtnCapture.jpg.
They were just 16 x 16 pixel bitmaps, you can make them up yourself.
5. I assume you've got the webcam working and the driver installed already.
Ps. if you find this useful, then reply back with where you are in the world. I'm in Dublin, Ireland.
cheers,
Owen
import javax.swing.*;
import javax.swing.border.*;
import java.io.*;
import javax.media.*;
import javax.media.format.*;
import javax.media.util.*;
import javax.media.control.*;
import java.util.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import com.sun.image.codec.jpeg.*;
// Ps. I think JMF 2.1.1c used a different package for this class..
import com.sun.media.vfw.VFWCapture;
public class JWebCam extends JFrame
                          implements WindowListener,
                                         ComponentListener
     protected final static int MIN_WIDTH  = 320;
     protected final static int MIN_HEIGHT = 240;
     protected static int shotCounter = 1;
     protected JLabel statusBar = null;
     protected Component visualComponent = null;
     protected JToolBar toolbar = null;
     protected MyToolBarAction formatButton  = null;
     protected MyToolBarAction captureButton = null;
    protected Player player = null;
    protected CaptureDeviceInfo webCamDeviceInfo = null;
    protected MediaLocator ml = null;
    protected Dimension imageSize = null;
    protected FormatControl formatControl = null;
    protected VideoFormat currentFormat = null;
    protected Format[] videoFormats = null;
    protected MyVideoFormat[] myFormatList = null;
      * Constructor
    public JWebCam ( String frameTitle )
         super ( frameTitle );
          try
              UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
         catch ( Exception cnfe )
              System.out.println ("Note : Cannot load look and feel settings");
         addWindowListener ( this );
         addComponentListener ( this );
         getContentPane().setLayout ( new BorderLayout() );
         statusBar = new JLabel ("Initialising...");
         statusBar.setBorder ( new EtchedBorder() );
         getContentPane().add ( statusBar, BorderLayout.SOUTH );
         setSize ( 320, 260 ); // default size...
         setVisible ( true );
      * Initialise
      * @returns true if web cam is detected
     public boolean initialise ( )
          throws Exception
          return ( initialise ( autoDetect() ) );
      * Initialise
      * @params _deviceInfo, specific web cam device if not autodetected
      * @returns true if web cam is detected
     public boolean initialise ( CaptureDeviceInfo _deviceInfo )
          throws Exception
          webCamDeviceInfo = _deviceInfo;
         if ( webCamDeviceInfo != null )
              statusBar.setText ( "Connecting to : " + webCamDeviceInfo.getName() );
              try
                    // setUpMenu ( );
                    setUpToolBar();
                    getContentPane().add ( toolbar, BorderLayout.NORTH );
                   ml = webCamDeviceInfo.getLocator();
                   if ( ml != null )
                      player = Manager.createRealizedPlayer ( ml );
                      if ( player != null )
                           formatControl = (FormatControl)player.getControl ( "javax.media.control.FormatControl" );
                                videoFormats = webCamDeviceInfo.getFormats();
                                setFormat ( (VideoFormat)videoFormats[0] );
                           // player.start();
                                visualComponent = player.getVisualComponent();
                                getContentPane().add ( visualComponent, BorderLayout.CENTER );
                                invalidate();
                                pack();
                                setSize ( imageSize.width, imageSize.height + statusBar.getHeight() + toolbar.getHeight() );
                            myFormatList = new MyVideoFormat[videoFormats.length];
                            for ( int i=0; i<videoFormats.length; i++ )
                                 myFormatList[i] = new MyVideoFormat ( (VideoFormat)videoFormats[i] );
                 else
                      statusBar.setText ( "No Media Locator for : " + webCamDeviceInfo.getName() );
                    return ( true );
               catch ( IOException ioEx )
                   statusBar.setText ( "Connecting to : " + webCamDeviceInfo.getName() );
                    return ( false );
               catch ( NoPlayerException npex )
                    statusBar.setText ("Cannot create player");
                    return ( false );
               catch ( CannotRealizeException nre )
                    statusBar.setText ( "Cannot realize player");
                    return ( false );
         else
              return ( false );
      * Dynamically create menu items
      * @returns the device info object if found, null otherwise
     public void setFormat ( VideoFormat selectedFormat )
          if ( formatControl != null )
               player.stop();
               statusBar.setText ( "Format : " + selectedFormat );
               imageSize = selectedFormat.getSize();
               formatControl.setFormat ( selectedFormat );
               currentFormat = selectedFormat;
               setSize ( imageSize.width, imageSize.height + statusBar.getHeight() + toolbar.getHeight() );
               player.start();
          else
               System.out.println ("Visual component not an instance of FormatControl");
               statusBar.setText ( "Visual component cannot change format" );
     protected void setUpToolBar ( )
          toolbar = new JToolBar();
          formatButton  = new MyToolBarAction ( "Format",  "BtnFormat.jpg" );
          captureButton = new MyToolBarAction ( "Capture", "BtnCapture.jpg" );
          if ( formatButton != null )
                toolbar.add ( formatButton );
          toolbar.add ( captureButton );
          getContentPane().add ( toolbar, BorderLayout.NORTH );
     protected void toolbarHandler ( MyToolBarAction actionBtn )
          if ( actionBtn == formatButton )
                  // JOptionPane.showConfirmDialog ( this, "Format Dialog" );
                  Object selected = JOptionPane.showInputDialog (this,
                                                                 "Select Video format",
                                                                 "Capture format selection",
                                                                 JOptionPane.INFORMATION_MESSAGE,
                                                                 null,          //     Icon icon,
                                                                 myFormatList, // videoFormats,
                                                                 currentFormat );
               if ( selected != null )
                    setFormat ( ((MyVideoFormat)selected).format );
          else if ( actionBtn == captureButton )
               Image photo = grabFrameImage ( );
               MySnapshot snapshot = new MySnapshot ( photo, new Dimension ( imageSize ) );
      * autoDetects the first web camera in the system
      * @returns the device info object if found, null otherwise
    public CaptureDeviceInfo autoDetect ( )
          Vector list = CaptureDeviceManager.getDeviceList ( null );
          CaptureDeviceInfo devInfo = null;
          if ( list != null )
               String name;
               for ( int i=0; i<list.size(); i++ )
                    devInfo = (CaptureDeviceInfo)list.elementAt ( i );
                    name = devInfo.getName();
                  if ( name.startsWith ("vfw:") )
                        break;
               if ( devInfo != null && devInfo.getName().startsWith("vfw:") )
                   return ( devInfo );
               else
                  for ( int i = 0; i < 10; i++ )
                       try
                           name = VFWCapture.capGetDriverDescriptionName ( i );
                           if (name != null && name.length() > 1)
                                   devInfo = com.sun.media.protocol.vfw.VFWSourceStream.autoDetect ( i );
                                   if ( devInfo != null )
                                        return ( devInfo );
                         catch ( Exception ioEx )
                              // ignore errors detecting device
                              statusBar.setText ( "AutoDetect failed : " + ioEx.getMessage() );
                   return ( null );
          else
               return ( null );
      * deviceInfo
      * @note outputs text information
     public void deviceInfo ( )
         if ( webCamDeviceInfo != null )
              Format[] formats = webCamDeviceInfo.getFormats();
              if ( ( formats != null ) && ( formats.length > 0 ) )
              for ( int i=0; i<formats.length; i++ )
                   Format aFormat = formats;
               if ( aFormat instanceof VideoFormat )
                    Dimension dim = ((VideoFormat)aFormat).getSize();
                    System.out.println ("Video Format " + i + " : " + formats[i].getEncoding() + ", " + dim.width + " x " + dim.height );
               else
                    System.out.println ("Format " + i + " : " + formats[i].getEncoding() );
     else
          System.out.println ("Error : No web cam detected");
     * grabs a frame's buffer from the web cam / device
     * @returns A frames buffer
     public Buffer grabFrameBuffer ( )
          if ( player != null )
FrameGrabbingControl fgc = (FrameGrabbingControl)player.getControl ( "javax.media.control.FrameGrabbingControl" );
Buffer buf = fgc.grabFrame();
return ( buf );
else
     return ( null );
     * grabs a frame's buffer, as an image, from the web cam / device
     * @returns A frames buffer as an image
     public Image grabFrameImage ( )
          Buffer buffer = grabFrameBuffer();
          if ( buffer != null )
// Convert it to an image
BufferToImage btoi = new BufferToImage ( (VideoFormat)buffer.getFormat() );
Image image = btoi.createImage ( buffer );
return ( image );
          else
               System.out.println ("Error : Buffer grabbed is null");
               return ( null );
     * Closes and cleans up the player
     public void playerClose ( )
          if ( player != null )
     player.close();
     player.deallocate();
     player = null;
     public void windowClosing ( WindowEvent e )
          playerClose();
          System.exit ( 1 );
     public void componentResized(ComponentEvent e)
          Dimension dim = getSize();
          boolean mustResize = false;
          if ( dim.width < MIN_WIDTH )
          dim.width = MIN_WIDTH;
          mustResize = true;
          if ( dim.height < MIN_HEIGHT )
               dim.height = MIN_HEIGHT;
               mustResize = true;
          if ( mustResize )
               setSize ( dim );
     public void windowActivated ( WindowEvent e )      {       }
     public void windowClosed ( WindowEvent e )      {       }
     public void windowDeactivated ( WindowEvent e )     {     }
     public void windowDeiconified ( WindowEvent e )     {     }
     public void windowIconified ( WindowEvent e )     {     }
     public void windowOpened ( WindowEvent e )          {     }
     public void componentHidden(ComponentEvent e)      {       }
     public void componentMoved(ComponentEvent e)     {     }
     public void componentShown(ComponentEvent e)     {     }
     protected void finalize     ( ) throws Throwable
          playerClose();
          super.finalize();
     class MyToolBarAction extends AbstractAction
          public MyToolBarAction ( String name, String imagefile )
               super ( name, new ImageIcon ( imagefile ) );
          public void actionPerformed ( ActionEvent event )
               toolbarHandler ( this );
     class MyVideoFormat
          public VideoFormat format;
          public MyVideoFormat ( VideoFormat _format )
               format = _format;
          public String toString ( )
               Dimension dim = format.getSize();
               return ( format.getEncoding() + " [ " + dim.width + " x " + dim.height + " ]" );
     class MySnapshot extends JFrame
          protected Image photo = null;
          protected int shotNumber;
          public MySnapshot ( Image grabbedFrame, Dimension imageSize )
               super ( );
               shotNumber = shotCounter++;
               setTitle ( "Photo" + shotNumber );
               photo = grabbedFrame;
               setDefaultCloseOperation ( WindowConstants.DO_NOTHING_ON_CLOSE );
               int imageHeight = photo.getWidth ( this );
               int imageWidth = photo.getHeight ( this );
               setSize ( imageSize.width, imageSize.height );
               final FileDialog saveDialog = new FileDialog ( this, "Save JPEG", FileDialog.SAVE );
               final JFrame thisCopy = this;
               saveDialog.setFile ( "Photo" + shotNumber );
               addWindowListener ( new WindowAdapter()
                         public void windowClosing ( WindowEvent e )
                              saveDialog.show();
                              String filename = saveDialog.getFile();
                              if ( filename != null )
                                   if ( saveJPEG ( filename ) )
                                        JOptionPane.showMessageDialog ( thisCopy, "Saved " + filename );
                                        setVisible ( false );
                                        dispose();
                                   else
                                        JOptionPane.showMessageDialog ( thisCopy, "Error saving " + filename );
                              else
                                   setVisible ( false );
                                   dispose();
               setVisible ( true );
          public void paint ( Graphics g )
               g.drawImage ( photo, 0, 0, getWidth(), getHeight(), this );
          * Saves an image as a JPEG
          * @params the image to save
          * @params the filename to save the image as
     public boolean saveJPEG ( String filename )
          boolean saved = false;
     BufferedImage bi = new BufferedImage ( photo.getWidth(null),
     photo.getHeight(null),
     BufferedImage.TYPE_INT_RGB );
     Graphics2D g2 = bi.createGraphics();
     g2.drawImage ( photo, null, null );
     FileOutputStream out = null;
     try
     out = new FileOutputStream ( filename );
          JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder ( out );
          JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam ( bi );
          param.setQuality ( 1.0f, false );
          encoder.setJPEGEncodeParam ( param );
          encoder.encode ( bi );
          out.close();
          saved = true;
     catch ( Exception ex )
     System.out.println ("Error saving JPEG : " + ex.getMessage() );
     return ( saved );
     }     // of MySnapshot
public static void main (String[] args )
     try
          JWebCam myWebCam = new JWebCam ( "TimeSlice Web Cam Capture" );
          if ( myWebCam.initialise() )
               // myWebCam.deviceInfo(); // outputs device info
          else
               System.out.println ("Web Cam not detected / initialised");
     catch ( Exception ex )
          ex.printStackTrace();

Doohhh... I posted an old version which didn't work.
I tried and tested this last night, and it runs grand using Ver 2.1.1e.
Tested under Windows 98, using an old Creative GO Camera.
Haven't tried it under Linux, but suspect you'd have to at least change an references to "vfw" to "v4l".
You'll need jmf.jar in your classpath to run it too.
cheers,
Owen
import javax.swing.*;
import javax.swing.border.*;
import java.io.*;
import javax.media.*;
import javax.media.datasink.*;
import javax.media.format.*;
import javax.media.protocol.*;
import javax.media.util.*;
import javax.media.control.*;
import java.util.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import com.sun.image.codec.jpeg.*;
// import com.sun.media.vfw.VFWCapture;         // JMF 2.1.1c version
import com.sun.media.protocol.vfw.VFWCapture;   // JMF 2.1.1e version
public class JWebCam extends JFrame
    implements WindowListener,  ComponentListener
    protected final static int MIN_WIDTH  = 320;
    protected final static int MIN_HEIGHT = 240;
    protected static int shotCounter = 1;
    protected JLabel statusBar = null;
    protected JPanel visualContainer = null;
    protected Component visualComponent = null;
    protected JToolBar toolbar = null;
    protected MyToolBarAction formatButton    = null;
    protected MyToolBarAction captureButton   = null;
    protected Player player = null;
    protected CaptureDeviceInfo webCamDeviceInfo = null;
    protected MediaLocator ml = null;
    protected Dimension imageSize = null;
    protected FormatControl formatControl = null;
    protected VideoFormat currentFormat = null;
    protected Format[] videoFormats = null;
    protected MyVideoFormat[] myFormatList = null;
    protected boolean initialised = false;
     * Constructor
    public JWebCam ( String frameTitle )
        super ( frameTitle );
        try
            UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
        catch ( Exception cnfe )
            System.out.println ("Note : Cannot load look and feel settings");
        setSize ( 320, 260 ); // default size...
        addWindowListener ( this );
        addComponentListener ( this );
        getContentPane().setLayout ( new BorderLayout() );
        visualContainer = new JPanel();
        visualContainer.setLayout ( new BorderLayout() );
        getContentPane().add ( visualContainer, BorderLayout.CENTER );
        statusBar = new JLabel ("");
        statusBar.setBorder ( new EtchedBorder() );
        getContentPane().add ( statusBar, BorderLayout.SOUTH );
     * Initialise
     * @returns true if web cam is detected
    public boolean initialise ( )
        throws Exception
        return ( initialise ( autoDetect() ) );
     * Initialise
     * @params _deviceInfo, specific web cam device if not autodetected
     * @returns true if web cam is detected
    public boolean initialise ( CaptureDeviceInfo _deviceInfo )
        throws Exception
        statusBar.setText ( "Initialising...");
        webCamDeviceInfo = _deviceInfo;
        if ( webCamDeviceInfo != null )
            statusBar.setText ( "Connecting to : " + webCamDeviceInfo.getName() );
            try
                setUpToolBar();
                getContentPane().add ( toolbar, BorderLayout.NORTH );
                ml = webCamDeviceInfo.getLocator();
                if ( ml != null )
                    player = Manager.createRealizedPlayer ( ml );
                    if ( player != null )
                        player.start();
                        formatControl = (FormatControl)player.getControl ( "javax.media.control.FormatControl" );
                        videoFormats = webCamDeviceInfo.getFormats();
                        visualComponent = player.getVisualComponent();
                        if ( visualComponent != null )
                            visualContainer.add ( visualComponent, BorderLayout.CENTER );
                            myFormatList = new MyVideoFormat[videoFormats.length];
                            for ( int i=0; i<videoFormats.length; i++ )
                                myFormatList[i] = new MyVideoFormat ( (VideoFormat)videoFormats[i] );
                            Format currFormat = formatControl.getFormat();
                            if ( currFormat instanceof VideoFormat )
                                 currentFormat = (VideoFormat)currFormat;
                                 imageSize = currentFormat.getSize();
                                 visualContainer.setPreferredSize ( imageSize );
                                 setSize ( imageSize.width, imageSize.height + statusBar.getHeight() + toolbar.getHeight() );
                            else
                                System.err.println ("Error : Cannot get current video format");
                            invalidate();
                            pack();
                            return ( true );
                        else
                            System.err.println ("Error : Could not get visual component");
                            return ( false );
                    else
                        System.err.println ("Error : Cannot create player");
                        statusBar.setText ( "Cannot create player" );
                        return ( false );
                else
                    System.err.println ("Error : No MediaLocator for " + webCamDeviceInfo.getName() );
                    statusBar.setText ( "No Media Locator for : " + webCamDeviceInfo.getName() );
                    return ( false );
            catch ( IOException ioEx )
                statusBar.setText ( "Connecting to : " + webCamDeviceInfo.getName() );
                return ( false );
            catch ( NoPlayerException npex )
                statusBar.setText ("Cannot create player");
                return ( false );
            catch ( CannotRealizeException nre )
                statusBar.setText ( "Cannot realize player");
                return ( false );
        else
            return ( false );
     * Dynamically create menu items
     * @returns the device info object if found, null otherwise
    public void setFormat ( VideoFormat selectedFormat )
        if ( formatControl != null )
            player.stop();
            imageSize = selectedFormat.getSize();
            formatControl.setFormat ( selectedFormat );
            player.start();
            statusBar.setText ( "Format : " + selectedFormat );
            currentFormat = selectedFormat;
            visualContainer.setPreferredSize ( currentFormat.getSize() );
            setSize ( imageSize.width, imageSize.height + statusBar.getHeight() + toolbar.getHeight() );
        else
            System.out.println ("Visual component not an instance of FormatControl");
            statusBar.setText ( "Visual component cannot change format" );
    public VideoFormat getFormat ( )
        return ( currentFormat );
    protected void setUpToolBar ( )
        toolbar = new JToolBar();
        // Note : If you supply the 16 x 16 bitmaps then you can replace
        // the commented line in the MyToolBarAction constructor
        formatButton    = new MyToolBarAction ( "Resolution", "BtnFormat.jpg" );
        captureButton   = new MyToolBarAction ( "Capture",    "BtnCapture.jpg" );
        toolbar.add ( formatButton );
        toolbar.add ( captureButton );
        getContentPane().add ( toolbar, BorderLayout.NORTH );
    protected void toolbarHandler ( MyToolBarAction actionBtn )
        if ( actionBtn == formatButton )
            Object selected = JOptionPane.showInputDialog (this,
                                                           "Select Video format",
                                                           "Capture format selection",
                                                           JOptionPane.INFORMATION_MESSAGE,
                                                           null,        //  Icon icon,
                                                           myFormatList, // videoFormats,
                                                           currentFormat );
            if ( selected != null )
                setFormat ( ((MyVideoFormat)selected).format );
        else if ( actionBtn == captureButton )
            Image photo = grabFrameImage ( );
            if ( photo != null )
                MySnapshot snapshot = new MySnapshot ( photo, new Dimension ( imageSize ) );
            else
                System.err.println ("Error : Could not grab frame");
     * autoDetects the first web camera in the system
     * searches for video for windows ( vfw ) capture devices
     * @returns the device info object if found, null otherwise
    public CaptureDeviceInfo autoDetect ( )
        Vector list = CaptureDeviceManager.getDeviceList ( null );
        CaptureDeviceInfo devInfo = null;
        if ( list != null )
            String name;
            for ( int i=0; i<list.size(); i++ )
                devInfo = (CaptureDeviceInfo)list.elementAt ( i );
                name = devInfo.getName();
                if ( name.startsWith ("vfw:") )
                    break;
            if ( devInfo != null && devInfo.getName().startsWith("vfw:") )
                return ( devInfo );
            else
                for ( int i = 0; i < 10; i++ )
                    try
                        name = VFWCapture.capGetDriverDescriptionName ( i );
                        if (name != null && name.length() > 1)
                            devInfo = com.sun.media.protocol.vfw.VFWSourceStream.autoDetect ( i );
                            if ( devInfo != null )
                                return ( devInfo );
                    catch ( Exception ioEx )
                        // ignore errors detecting device
                        statusBar.setText ( "AutoDetect failed : " + ioEx.getMessage() );
                return ( null );
        else
            return ( null );
     * deviceInfo
     * @note outputs text information
    public void deviceInfo ( )
        if ( webCamDeviceInfo != null )
            Format[] formats = webCamDeviceInfo.getFormats();
            if ( ( formats != null ) && ( formats.length > 0 ) )
            for ( int i=0; i<formats.length; i++ )
                Format aFormat = formats;
if ( aFormat instanceof VideoFormat )
Dimension dim = ((VideoFormat)aFormat).getSize();
// System.out.println ("Video Format " + i + " : " + formats[i].getEncoding() + ", " + dim.width + " x " + dim.height );
else
System.out.println ("Error : No web cam detected");
* grabs a frame's buffer from the web cam / device
* @returns A frames buffer
public Buffer grabFrameBuffer ( )
if ( player != null )
FrameGrabbingControl fgc = (FrameGrabbingControl)player.getControl ( "javax.media.control.FrameGrabbingControl" );
if ( fgc != null )
return ( fgc.grabFrame(); );
else
System.err.println ("Error : FrameGrabbingControl is null");
return ( null );
else
System.err.println ("Error : Player is null");
return ( null );
* grabs a frame's buffer, as an image, from the web cam / device
* @returns A frames buffer as an image
public Image grabFrameImage ( )
Buffer buffer = grabFrameBuffer();
if ( buffer != null )
// Convert it to an image
BufferToImage btoi = new BufferToImage ( (VideoFormat)buffer.getFormat() );
if ( btoi != null )
Image image = btoi.createImage ( buffer );
if ( image != null )
return ( image );
else
System.err.println ("Error : BufferToImage cannot convert buffer");
return ( null );
else
System.err.println ("Error : cannot create BufferToImage instance");
return ( null );
else
System.out.println ("Error : Buffer grabbed is null");
return ( null );
* Closes and cleans up the player
public void playerClose ( )
if ( player != null )
player.close();
player.deallocate();
player = null;
public void windowClosing ( WindowEvent e )
playerClose();
System.exit ( 1 );
public void componentResized ( ComponentEvent e )
Dimension dim = getSize();
boolean mustResize = false;
if ( dim.width < MIN_WIDTH )
dim.width = MIN_WIDTH;
mustResize = true;
if ( dim.height < MIN_HEIGHT )
dim.height = MIN_HEIGHT;
mustResize = true;
if ( mustResize )
setSize ( dim );
public void windowActivated ( WindowEvent e ) {   }
public void windowClosed ( WindowEvent e ) {   }
public void windowDeactivated ( WindowEvent e ) {   }
public void windowDeiconified ( WindowEvent e ) {   }
public void windowIconified ( WindowEvent e ) {   }
public void windowOpened ( WindowEvent e ) {   }
public void componentHidden(ComponentEvent e) {   }
public void componentMoved(ComponentEvent e) {   }
public void componentShown(ComponentEvent e) {   }
protected void finalize ( ) throws Throwable
playerClose();
super.finalize();
class MyToolBarAction extends AbstractAction
public MyToolBarAction ( String name, String imagefile )
// Note : Use version this if you supply your own toolbar icons
// super ( name, new ImageIcon ( imagefile ) );
super ( name );
public void actionPerformed ( ActionEvent event )
toolbarHandler ( this );
class MyVideoFormat
public VideoFormat format;
public MyVideoFormat ( VideoFormat _format )
format = _format;
public String toString ( )
Dimension dim = format.getSize();
return ( format.getEncoding() + " [ " + dim.width + " x " + dim.height + " ]" );
class MySnapshot extends JFrame
protected Image photo = null;
protected int shotNumber;
public MySnapshot ( Image grabbedFrame, Dimension imageSize )
super ( );
shotNumber = shotCounter++;
setTitle ( "Photo" + shotNumber );
photo = grabbedFrame;
setDefaultCloseOperation ( WindowConstants.DISPOSE_ON_CLOSE );
int imageHeight = photo.getWidth ( this );
int imageWidth = photo.getHeight ( this );
setSize ( imageSize.width, imageSize.height );
final FileDialog saveDialog = new FileDialog ( this, "Save JPEG", FileDialog.SAVE );
final JFrame thisCopy = this;
saveDialog.setFile ( "Photo" + shotNumber );
addWindowListener ( new WindowAdapter()
public void windowClosing ( WindowEvent e )
saveDialog.show();
String filename = saveDialog.getFile();
if ( filename != null )
if ( saveJPEG ( filename ) )
JOptionPane.showMessageDialog ( thisCopy, "Saved " + filename );
setVisible ( false );
dispose();
else
JOptionPane.showMessageDialog ( thisCopy, "Error saving " + filename );
else
setVisible ( false );
dispose();
setVisible ( true );
public void paint ( Graphics g )
g.drawImage ( photo, 0, 0, getWidth(), getHeight(), this );
* Saves an image as a JPEG
* @params the image to save
* @params the filename to save the image as
public boolean saveJPEG ( String filename )
boolean saved = false;
BufferedImage bi = new BufferedImage ( photo.getWidth(null),
photo.getHeight(null),
BufferedImage.TYPE_INT_RGB );
Graphics2D g2 = bi.createGraphics();
g2.drawImage ( photo, null, null );
FileOutputStream out = null;
try
out = new FileOutputStream ( filename );
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder ( out );
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam ( bi );
param.setQuality ( 1.0f, false ); // 100% high quality setting, no compression
encoder.setJPEGEncodeParam ( param );
encoder.encode ( bi );
out.close();
saved = true;
catch ( Exception ex )
System.out.println ("Error saving JPEG : " + ex.getMessage() );
return ( saved );
} // of MySnapshot
public static void main (String[] args )
try
JWebCam myWebCam = new JWebCam ( "TimeSlice Web Cam Capture" );
myWebCam.setVisible ( true );
if ( !myWebCam.initialise() )
System.out.println ("Web Cam not detected / initialised");
catch ( Exception ex )
ex.printStackTrace();

Similar Messages

  • Updated : No question, just example web cam capture code

    Hi,
    I posted this example a while back, but it had some cosmetic bugs in it.
    Here's an updated version.
    Quick Start
    1. Install JMF 2.1.1e (performance pack version)
    ( see imports list in source code if you really want to run it using the older version 2.1.1c )
    2. You have to set the JMF_HOME or JMFHOME environment variable. Can't remember which one.
    "Nearly sure" it's JMF_HOME.
    3. Connect your camera
    4. run jmfinit ( may need to do a few times until it detects your camera )
    When it does, you're in business, and you can try to run the code
    5. Run java -cp .;%JMF_HOME%\lib\jmf.jar JWebCam
    known issue
    Under Java 1.5 / 5 - When capturing a frame, and then resizing that snapshots JFrame, the image did not always scale up and display.
    That does work under Java 1.3.1_06 .
    Tested on Win98 2nd edition, Java 1.3.1_06, and Creative Web Cam Pro.
    Legal stuff in plain english : This code is available for use by everyone, personal or commercial, no need to mention me in licenses or anything. It's just a demo I knocked up for myself. So I am under no obligation to support this. Use it at your own risk.... that implies you can't blame or sue me for anything that goes wrong.
    If you like the code, I'd be happy to hear whereabouts you are in the world :-)
    Also note : this is the limits of my JMF experience at present.
    If you've a separate question, post it to a new topic!
    regards,
    Owen ( Dublin, Ireland )
    import javax.swing.*;
    import javax.swing.border.*;
    import java.io.*;
    import javax.media.*;
    import javax.media.datasink.*;
    import javax.media.format.*;
    import javax.media.protocol.*;
    import javax.media.util.*;
    import javax.media.control.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    import com.sun.image.codec.jpeg.*;
    // import com.sun.media.vfw.VFWCapture;         // JMF 2.1.1c version
    import com.sun.media.protocol.vfw.VFWCapture;   // JMF 2.1.1e version
    public class JWebCam extends JFrame
        implements WindowListener,  ComponentListener
        protected final static int MIN_WIDTH  = 100;  // 320;
        protected final static int MIN_HEIGHT = 100;  // 240;
        protected static int shotCounter = 1;
        protected JLabel statusBar = null;
        protected JPanel visualContainer = null;
        protected Component visualComponent = null;
        protected JToolBar toolbar = null;
        protected MyToolBarAction formatButton    = null;
        protected MyToolBarAction captureButton   = null;
        protected Player player = null;
        protected CaptureDeviceInfo webCamDeviceInfo = null;
        protected MediaLocator ml = null;
        protected Dimension imageSize = null;
        protected FormatControl formatControl = null;
        protected VideoFormat currentFormat = null;
        protected Format[] videoFormats = null;
        protected MyVideoFormat[] myFormatList = null;
        protected MyCaptureDeviceInfo[] myCaptureDevices = null;
        protected boolean initialised = false;
         * Constructor
        public JWebCam ( String frameTitle )
            super ( frameTitle );
            try
                UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
            catch ( Exception cnfe )
                System.out.println ("Note : Cannot load look and feel settings");
            setSize ( 320, 260 ); // default size...
            addWindowListener ( this );
            addComponentListener ( this );
            getContentPane().setLayout ( new BorderLayout() );
            visualContainer = new JPanel();
            visualContainer.setLayout ( new BorderLayout() );
            getContentPane().add ( visualContainer, BorderLayout.CENTER );
            statusBar = new JLabel ("")
                // Nasty bug workaround
                // The minimum JLabel size was determined by the text in the status bar
                // So the layoutmanager wouldn't shrink the window for the video image
                public Dimension getPreferredSize (  )
                    // get the JLabel to "allow" a minimum of 10 pixels width
                    // not to work out the minimum size from the text length
                    return ( new Dimension ( 10, super.getPreferredSize().height ) );
            statusBar.setBorder ( new EtchedBorder() );
            getContentPane().add ( statusBar, BorderLayout.SOUTH );
         * Initialise
         * @returns true if web cam is detected
        public boolean initialise ( )
            throws Exception
            MyCaptureDeviceInfo[] cams = autoDetect();
            if ( cams.length > 0 )
                if ( cams.length == 1 )
                     System.out.println ("Note : 1 web cam detected");
                     return ( initialise ( cams[0].capDevInfo ) );
                else
                    System.out.println ("Note : " + cams.length + " web cams detected");
                    Object selected = JOptionPane.showInputDialog (this,
                                                                   "Select Video format",
                                                                   "Capture format selection",
                                                                   JOptionPane.INFORMATION_MESSAGE,
                                                                   null,        //  Icon icon,
                                                                   cams, // videoFormats,
                                                                   cams[0] );
                    if ( selected != null )
                        return ( initialise ( ((MyCaptureDeviceInfo)selected).capDevInfo ) );
                    else
                        return ( initialise ( null ) );
            else
                return ( initialise ( null ) );
         * Initialise
         * @params _deviceInfo, specific web cam device if not autodetected
         * @returns true if web cam is detected
        public boolean initialise ( CaptureDeviceInfo _deviceInfo )
            throws Exception
            statusBar.setText ( "Initialising...");
            webCamDeviceInfo = _deviceInfo;
            if ( webCamDeviceInfo != null )
                statusBar.setText ( "Connecting to : " + webCamDeviceInfo.getName() );
                try
                    setUpToolBar();
                    getContentPane().add ( toolbar, BorderLayout.NORTH );
                    ml = webCamDeviceInfo.getLocator();
                    if ( ml != null )
                        player = Manager.createRealizedPlayer ( ml );
                        if ( player != null )
                            player.start();
                            formatControl = (FormatControl)player.getControl ( "javax.media.control.FormatControl" );
                            videoFormats = webCamDeviceInfo.getFormats();
                            myFormatList = new MyVideoFormat[videoFormats.length];
                            for ( int i=0; i<videoFormats.length; i++ )
                                myFormatList[i] = new MyVideoFormat ( (VideoFormat)videoFormats[i] );
                            Format currFormat = formatControl.getFormat();
                            visualComponent = player.getVisualComponent();
                            if ( visualComponent != null )
                                visualContainer.add ( visualComponent, BorderLayout.CENTER );
                                if ( currFormat instanceof VideoFormat )
                                     currentFormat = (VideoFormat)currFormat;
                                     imageSize = currentFormat.getSize();
                                     visualContainer.setPreferredSize ( imageSize );
                                     setSize ( imageSize.width, imageSize.height + statusBar.getHeight() + toolbar.getHeight() );
                                else
                                    System.err.println ("Error : Cannot get current video format");
                                invalidate();
                                pack();
                                return ( true );
                            else
                                System.err.println ("Error : Could not get visual component");
                                return ( false );
                        else
                            System.err.println ("Error : Cannot create player");
                            statusBar.setText ( "Cannot create player" );
                            return ( false );
                    else
                        System.err.println ("Error : No MediaLocator for " + webCamDeviceInfo.getName() );
                        statusBar.setText ( "No Media Locator for : " + webCamDeviceInfo.getName() );
                        return ( false );
                catch ( IOException ioEx )
                    System.err.println ("Error connecting to [" + webCamDeviceInfo.getName() + "] : " + ioEx.getMessage() );
                    statusBar.setText ( "Connecting to : " + webCamDeviceInfo.getName() );
                    return ( false );
                catch ( NoPlayerException npex )
                    statusBar.setText ("Cannot create player");
                    return ( false );
                catch ( CannotRealizeException nre )
                    statusBar.setText ( "Cannot realize player");
                    return ( false );
            else
                return ( false );
         * Dynamically create menu items
         * @returns the device info object if found, null otherwise
        public void setFormat ( VideoFormat selectedFormat )
            if ( formatControl != null )
                // player.stop();       // not needed and big performance hit
                currentFormat = selectedFormat;
                if ( visualComponent != null )
                     visualContainer.remove ( visualComponent );
                imageSize = currentFormat.getSize();
                visualContainer.setPreferredSize ( imageSize );
                statusBar.setText ( "Format : " + currentFormat );
                System.out.println ("Format : " + currentFormat );
                formatControl.setFormat ( currentFormat );
                // player.start();  // not needed and big performance hit
                visualComponent = player.getVisualComponent();
                if ( visualComponent != null )
                    visualContainer.add ( visualComponent, BorderLayout.CENTER );
                invalidate();       // let the layout manager work out the sizes
                pack();
            else
                System.out.println ("Visual component not an instance of FormatControl");
                statusBar.setText ( "Visual component cannot change format" );
        public VideoFormat getFormat ( )
            return ( currentFormat );
        protected void setUpToolBar ( )
            toolbar = new JToolBar();
            // Note : due to cosmetic glitches when undocking and docking the toolbar,
            //        I've set this to false.
            toolbar.setFloatable(false);
            // Note : If you supply the 16 x 16 bitmaps then you can replace
            // the commented line in the MyToolBarAction constructor
            formatButton    = new MyToolBarAction ( "Resolution", "BtnFormat.jpg" );
            captureButton   = new MyToolBarAction ( "Capture",    "BtnCapture.jpg" );
            toolbar.add ( formatButton );
            toolbar.add ( captureButton );
            getContentPane().add ( toolbar, BorderLayout.NORTH );
        protected void toolbarHandler ( MyToolBarAction actionBtn )
            if ( actionBtn == formatButton )
                Object selected = JOptionPane.showInputDialog (this,
                                                               "Select Video format",
                                                               "Capture format selection",
                                                               JOptionPane.INFORMATION_MESSAGE,
                                                               null,        //  Icon icon,
                                                               myFormatList, // videoFormats,
                                                               currentFormat );
                if ( selected != null )
                    setFormat ( ((MyVideoFormat)selected).format );
            else if ( actionBtn == captureButton )
                Image photo = grabFrameImage ( );
                if ( photo != null )
                    MySnapshot snapshot = new MySnapshot ( photo, new Dimension ( imageSize ) );
                else
                    System.err.println ("Error : Could not grab frame");
         * autoDetects the first web camera in the system
         * searches for video for windows ( vfw ) capture devices
         * @returns the device info object if found, null otherwise
        public MyCaptureDeviceInfo[] autoDetect ( )
            Vector list = CaptureDeviceManager.getDeviceList ( null );
            CaptureDeviceInfo devInfo = null;
            String name;
            Vector capDevices = new Vector();
            if ( list != null )
                for ( int i=0; i<list.size(); i++ )
                    devInfo = (CaptureDeviceInfo)list.elementAt ( i );
                    name = devInfo.getName();
                    if ( name.startsWith ("vfw:") )
                        System.out.println ("DeviceManager List : " + name );
                        capDevices.addElement ( new MyCaptureDeviceInfo ( devInfo ) );
            else
                for ( int i = 0; i < 10; i++ )
                    try
                        name = VFWCapture.capGetDriverDescriptionName ( i );
                        if (name != null && name.length() > 1)
                            devInfo = com.sun.media.protocol.vfw.VFWSourceStream.autoDetect ( i );
                            if ( devInfo != null )
                                System.out.println ("VFW Autodetect List : " + name );
                                capDevices.addElement ( new MyCaptureDeviceInfo ( devInfo ) );
                    catch ( Exception ioEx )
                        System.err.println ("Error connecting to [" + webCamDeviceInfo.getName() + "] : " + ioEx.getMessage() );
                        // ignore errors detecting device
                        statusBar.setText ( "AutoDetect failed : " + ioEx.getMessage() );
            MyCaptureDeviceInfo[] detected = new MyCaptureDeviceInfo[ capDevices.size() ];
            for ( int i=0; i<capDevices.size(); i++ )
                detected[i] = (MyCaptureDeviceInfo)capDevices.elementAt ( i );
            return ( detected );
         * deviceInfo
         * @note outputs text information
        public void deviceInfo ( )
            if ( webCamDeviceInfo != null )
                Format[] formats = webCamDeviceInfo.getFormats();
                if ( ( formats != null ) && ( formats.length > 0 ) )
                for ( int i=0; i<formats.length; i++ )
                    Format aFormat = formats;
    if ( aFormat instanceof VideoFormat )
    Dimension dim = ((VideoFormat)aFormat).getSize();
    // System.out.println ("Video Format " + i + " : " + formats[i].getEncoding() + ", " + dim.width + " x " + dim.height );
    else
    System.out.println ("Error : No web cam detected");
    * grabs a frame's buffer from the web cam / device
    * @returns A frames buffer
    public Buffer grabFrameBuffer ( )
    if ( player != null )
    FrameGrabbingControl fgc = (FrameGrabbingControl)player.getControl ( "javax.media.control.FrameGrabbingControl" );
    if ( fgc != null )
    return ( fgc.grabFrame() );
    else
    System.err.println ("Error : FrameGrabbingControl is null");
    return ( null );
    else
    System.err.println ("Error : Player is null");
    return ( null );
    * grabs a frame's buffer, as an image, from the web cam / device
    * @returns A frames buffer as an image
    public Image grabFrameImage ( )
    Buffer buffer = grabFrameBuffer();
    if ( buffer != null )
    // Convert it to an image
    BufferToImage btoi = new BufferToImage ( (VideoFormat)buffer.getFormat() );
    if ( btoi != null )
    Image image = btoi.createImage ( buffer );
    if ( image != null )
    return ( image );
    else
    System.err.println ("Error : BufferToImage cannot convert buffer");
    return ( null );
    else
    System.err.println ("Error : cannot create BufferToImage instance");
    return ( null );
    else
    System.out.println ("Error : Buffer grabbed is null");
    return ( null );
    * Closes and cleans up the player
    public void playerClose ( )
    if ( player != null )
    player.close();
    player.deallocate();
    player = null;
    public void windowClosing ( WindowEvent e )
    playerClose();
    System.exit ( 1 );
    public void componentResized ( ComponentEvent e )
    Dimension dim = getSize();
    boolean mustResize = false;
    if ( dim.width < MIN_WIDTH )
    dim.width = MIN_WIDTH;
    mustResize = true;
    if ( dim.height < MIN_HEIGHT )
    dim.height = MIN_HEIGHT;
    mustResize = true;
    if ( mustResize )
    setSize ( dim );
    public void windowActivated ( WindowEvent e ) {   }
    public void windowClosed ( WindowEvent e ) {   }
    public void windowDeactivated ( WindowEvent e ) {   }
    public void windowDeiconified ( WindowEvent e ) {   }
    public void windowIconified ( WindowEvent e ) {   }
    public void windowOpened ( WindowEvent e ) {   }
    public void componentHidden(ComponentEvent e) {   }
    public void componentMoved(ComponentEvent e) {   }
    public void componentShown(ComponentEvent e) {   }
    protected void finalize ( ) throws Throwable
    playerClose();
    super.finalize();
    class MyToolBarAction extends AbstractAction
    public MyToolBarAction ( String name, String imagefile )
    // Note : Use version this if you supply your own toolbar icons
    // super ( name, new ImageIcon ( imagefile ) );
    super ( name );
    public void actionPerformed ( ActionEvent event )
    toolbarHandler ( this );
    class MyVideoFormat
    public VideoFormat format;
    public MyVideoFormat ( VideoFormat format )
    this.format = format;
    public String toString ( )
    Dimension dim = format.getSize();
    return ( format.getEncoding() + " [ " + dim.width + " x " + dim.height + " ]" );
    class MyCaptureDeviceInfo
    public CaptureDeviceInfo capDevInfo;
    public MyCaptureDeviceInfo ( CaptureDeviceInfo devInfo )
    capDevInfo = devInfo;
    public String toString ( )
    return ( capDevInfo.getName() );
    class MySnapshot extends JFrame implements ImageObserver
    protected Image photo = null;
    protected int shotNumber;
    public MySnapshot ( Image grabbedFrame, Dimension imageSize )
    super ( );
    shotNumber = shotCounter++;
    setTitle ( "Photo" + shotNumber );
    photo = grabbedFrame;
    setDefaultCloseOperation ( WindowConstants.DISPOSE_ON_CLOSE );
    int imageHeight = photo.getWidth ( this );
    int imageWidth = photo.getHeight ( this );
    setSize ( imageSize.width, imageSize.height );
    final FileDialog saveDialog = new FileDialog ( this, "Save JPEG", FileDialog.SAVE );
    final JFrame thisCopy = this;
    saveDialog.setFile ( "Photo" + shotNumber );
    addWindowListener ( new WindowAdapter()
    public void windowClosing ( WindowEvent e )
    saveDialog.show();
    String filename = saveDialog.getFile();
    if ( filename != null )
    if ( saveJPEG ( filename ) )
    JOptionPane.showMessageDialog ( thisCopy, "Saved " + filename );
    setVisible ( false );
    dispose();
    else
    JOptionPane.showMessageDialog ( thisCopy, "Error saving " + filename );
    else
    setVisible ( false );
    dispose();
    setVisible ( true );
    public void paint ( Graphics g )
    super.paint ( g );
    g.drawImage ( photo, 0, 0, getWidth(), getHeight(), Color.black, this );
    * Saves an image as a JPEG
    * @params the image to save
    * @params the filename to save the image as
    public boolean saveJPEG ( String filename )
    boolean saved = false;
    BufferedImage bi = new BufferedImage ( photo.getWidth(null),
    photo.getHeight(null),
    BufferedImage.TYPE_INT_RGB );
    Graphics2D g2 = bi.createGraphics();
    g2.drawImage ( photo, null, null );
    FileOutputStream out = null;
    try
    out = new FileOutputStream ( filename );
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder ( out );
    JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam ( bi );
    param.setQuality ( 1.0f, false ); // 100% high quality setting, no compression
    encoder.setJPEGEncodeParam ( param );
    encoder.encode ( bi );
    out.close();
    saved = true;
    catch ( Exception ex )
    System.out.println ("Error saving JPEG : " + ex.getMessage() );
    return ( saved );
    } // of MySnapshot
    public static void main (String[] args )
    try
    JWebCam myWebCam = new JWebCam ( "Web Cam Capture" );
    myWebCam.setVisible ( true );
    if ( !myWebCam.initialise() )
    System.out.println ("Web Cam not detected / initialised");
    catch ( Exception ex )
    ex.printStackTrace();

    Hi,
    Here's a working version.
    If there are no spaces after the "<" symbol, it thinks it's a HTML tag.
    Putting spaces in, stops this.
    cheers,
    Owen
    import javax.swing.*;
    import javax.swing.border.*;
    import java.io.*;
    import javax.media.*;
    import javax.media.datasink.*;
    import javax.media.format.*;
    import javax.media.protocol.*;
    import javax.media.util.*;
    import javax.media.control.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    import com.sun.image.codec.jpeg.*;
    // import com.sun.media.vfw.VFWCapture;         // JMF 2.1.1c version
    import com.sun.media.protocol.vfw.VFWCapture;   // JMF 2.1.1e version
    public class JWebCam extends JFrame
        implements WindowListener,  ComponentListener
        protected final static int MIN_WIDTH  = 100;  // 320;
        protected final static int MIN_HEIGHT = 100;  // 240;
        protected static int shotCounter = 1;
        protected JLabel statusBar = null;
        protected JPanel visualContainer = null;
        protected Component visualComponent = null;
        protected JToolBar toolbar = null;
        protected MyToolBarAction formatButton    = null;
        protected MyToolBarAction captureButton   = null;
        protected Player player = null;
        protected CaptureDeviceInfo webCamDeviceInfo = null;
        protected MediaLocator ml = null;
        protected Dimension imageSize = null;
        protected FormatControl formatControl = null;
        protected VideoFormat currentFormat = null;
        protected Format[] videoFormats = null;
        protected MyVideoFormat[] myFormatList = null;
        protected MyCaptureDeviceInfo[] myCaptureDevices = null;
        protected boolean initialised = false;
         * Constructor
        public JWebCam ( String frameTitle )
            super ( frameTitle );
            try
                UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
            catch ( Exception cnfe )
                System.out.println ("Note : Cannot load look and feel settings");
            setSize ( 320, 260 ); // default size...
            addWindowListener ( this );
            addComponentListener ( this );
            getContentPane().setLayout ( new BorderLayout() );
            visualContainer = new JPanel();
            visualContainer.setLayout ( new BorderLayout() );
            getContentPane().add ( visualContainer, BorderLayout.CENTER );
            statusBar = new JLabel ("")
                // Nasty bug workaround
                // The minimum JLabel size was determined by the text in the status bar
                // So the layoutmanager wouldn't shrink the window for the video image
                public Dimension getPreferredSize (  )
                    // get the JLabel to "allow" a minimum of 10 pixels width
                    // not to work out the minimum size from the text length
                    return ( new Dimension ( 10, super.getPreferredSize().height ) );
            statusBar.setBorder ( new EtchedBorder() );
            getContentPane().add ( statusBar, BorderLayout.SOUTH );
         * Initialise
         * @returns true if web cam is detected
        public boolean initialise ( )
            throws Exception
            MyCaptureDeviceInfo[] cams = autoDetect();
            if ( cams.length > 0 )
                if ( cams.length == 1 )
                     System.out.println ("Note : 1 web cam detected");
                     return ( initialise ( cams[0].capDevInfo ) );
                else
                    System.out.println ("Note : " + cams.length + " web cams detected");
                    Object selected = JOptionPane.showInputDialog (this,
                                                                   "Select Video format",
                                                                   "Capture format selection",
                                                                   JOptionPane.INFORMATION_MESSAGE,
                                                                   null,        //  Icon icon,
                                                                   cams, // videoFormats,
                                                                   cams[0] );
                    if ( selected != null )
                        return ( initialise ( ((MyCaptureDeviceInfo)selected).capDevInfo ) );
                    else
                        return ( initialise ( null ) );
            else
                return ( initialise ( null ) );
         * Initialise
         * @params _deviceInfo, specific web cam device if not autodetected
         * @returns true if web cam is detected
        public boolean initialise ( CaptureDeviceInfo _deviceInfo )
            throws Exception
            statusBar.setText ( "Initialising...");
            webCamDeviceInfo = _deviceInfo;
            if ( webCamDeviceInfo != null )
                statusBar.setText ( "Connecting to : " + webCamDeviceInfo.getName() );
                try
                    setUpToolBar();
                    getContentPane().add ( toolbar, BorderLayout.NORTH );
                    ml = webCamDeviceInfo.getLocator();
                    if ( ml != null )
                        player = Manager.createRealizedPlayer ( ml );
                        if ( player != null )
                            player.start();
                            formatControl = (FormatControl)player.getControl ( "javax.media.control.FormatControl" );
                            videoFormats = webCamDeviceInfo.getFormats();
                            myFormatList = new MyVideoFormat[videoFormats.length];
                            for ( int i=0; i < videoFormats.length; i++ )
                                myFormatList[i] = new MyVideoFormat ( (VideoFormat)videoFormats[i] );
                            Format currFormat = formatControl.getFormat();
                            visualComponent = player.getVisualComponent();
                            if ( visualComponent != null )
                                visualContainer.add ( visualComponent, BorderLayout.CENTER );
                                if ( currFormat instanceof VideoFormat )
                                     currentFormat = (VideoFormat)currFormat;
                                     imageSize = currentFormat.getSize();
                                     visualContainer.setPreferredSize ( imageSize );
                                     setSize ( imageSize.width, imageSize.height + statusBar.getHeight() + toolbar.getHeight() );
                                else
                                    System.err.println ("Error : Cannot get current video format");
                                invalidate();
                                pack();
                                return ( true );
                            else
                                System.err.println ("Error : Could not get visual component");
                                return ( false );
                        else
                            System.err.println ("Error : Cannot create player");
                            statusBar.setText ( "Cannot create player" );
                            return ( false );
                    else
                        System.err.println ("Error : No MediaLocator for " + webCamDeviceInfo.getName() );
                        statusBar.setText ( "No Media Locator for : " + webCamDeviceInfo.getName() );
                        return ( false );
                catch ( IOException ioEx )
                    System.err.println ("Error connecting to [" + webCamDeviceInfo.getName() + "] : " + ioEx.getMessage() );
                    statusBar.setText ( "Connecting to : " + webCamDeviceInfo.getName() );
                    return ( false );
                catch ( NoPlayerException npex )
                    statusBar.setText ("Cannot create player");
                    return ( false );
                catch ( CannotRealizeException nre )
                    statusBar.setText ( "Cannot realize player");
                    return ( false );
            else
                return ( false );
         * Dynamically create menu items
         * @returns the device info object if found, null otherwise
        public void setFormat ( VideoFormat selectedFormat )
            if ( formatControl != null )
                player.stop();
                currentFormat = selectedFormat;
                if ( visualComponent != null )
                     visualContainer.remove ( visualComponent );
                imageSize = currentFormat.getSize();
                visualContainer.setPreferredSize ( imageSize );
                statusBar.setText ( "Format : " + currentFormat );
                System.out.println ("Format : " + currentFormat );
                formatControl.setFormat ( currentFormat );
                player.start();
                visualComponent = player.getVisualComponent();
                if ( visualComponent != null )
                    visualContainer.add ( visualComponent, BorderLayout.CENTER );
                invalidate();       // let the layout manager work out the sizes
                pack();
            else
                System.out.println ("Visual component not an instance of FormatControl");
                statusBar.setText ( "Visual component cannot change format" );
        public VideoFormat getFormat ( )
            return ( currentFormat );
        protected void setUpToolBar ( )
            toolbar = new JToolBar();
            // Note : due to cosmetic glitches when undocking and docking the toolbar,
            //        I've set this to false.
            toolbar.setFloatable(false);
            // Note : If you supply the 16 x 16 bitmaps then you can replace
            // the commented line in the MyToolBarAction constructor
            formatButton    = new MyToolBarAction ( "Resolution", "BtnFormat.jpg" );
            captureButton   = new MyToolBarAction ( "Capture",    "BtnCapture.jpg" );
            toolbar.add ( formatButton );
            toolbar.add ( captureButton );
            getContentPane().add ( toolbar, BorderLayout.NORTH );
        protected void toolbarHandler ( MyToolBarAction actionBtn )
            if ( actionBtn == formatButton )
                Object selected = JOptionPane.showInputDialog (this,
                                                               "Select Video format",
                                                               "Capture format selection",
                                                               JOptionPane.INFORMATION_MESSAGE,
                                                               null,        //  Icon icon,
                                                               myFormatList, // videoFormats,
                                                               currentFormat );
                if ( selected != null )
                    setFormat ( ((MyVideoFormat)selected).format );
            else if ( actionBtn == captureButton )
                Image photo = grabFrameImage ( );
                if ( photo != null )
                    MySnapshot snapshot = new MySnapshot ( photo, new Dimension ( imageSize ) );
                else
                    System.err.println ("Error : Could not grab frame");
         * autoDetects the first web camera in the system
         * searches for video for windows ( vfw ) capture devices
         * @returns the device info object if found, null otherwise
        public MyCaptureDeviceInfo[] autoDetect ( )
            Vector list = CaptureDeviceManager.getDeviceList ( null );
            CaptureDeviceInfo devInfo = null;
            String name;
            Vector capDevices = new Vector();
            if ( list != null )
                for ( int i=0; i < list.size(); i++ )
                    devInfo = (CaptureDeviceInfo)list.elementAt ( i );
                    name = devInfo.getName();
                    if ( name.startsWith ("vfw:") )
                        System.out.println ("DeviceManager List : " + name );
                        capDevices.addElement ( new MyCaptureDeviceInfo ( devInfo ) );
            else
                for ( int i = 0; i < 10; i++ )
                    try
                        name = VFWCapture.capGetDriverDescriptionName ( i );
                        if (name != null && name.length() > 1)
                            devInfo = com.sun.media.protocol.vfw.VFWSourceStream.autoDetect ( i );
                            if ( devInfo != null )
                                System.out.println ("VFW Autodetect List : " + name );
                                capDevices.addElement ( new MyCaptureDeviceInfo ( devInfo ) );
                    catch ( Exception ioEx )
                        System.err.println ("Error connecting to [" + webCamDeviceInfo.getName() + "] : " + ioEx.getMessage() );
                        // ignore errors detecting device
                        statusBar.setText ( "AutoDetect failed : " + ioEx.getMessage() );
            MyCaptureDeviceInfo[] detected = new MyCaptureDeviceInfo[ capDevices.size() ];
            for ( int i=0; i < capDevices.size(); i++ )
                detected[i] = (MyCaptureDeviceInfo)capDevices.elementAt ( i );
            return ( detected );
         * deviceInfo
         * @note outputs text information
        public void deviceInfo ( )
            if ( webCamDeviceInfo != null )
                Format[] formats = webCamDeviceInfo.getFormats();
                if ( ( formats != null ) && ( formats.length > 0 ) )
                for ( int i=0; i < formats.length; i++ )
                    Format aFormat = formats;
    if ( aFormat instanceof VideoFormat )
    Dimension dim = ((VideoFormat)aFormat).getSize();
    // System.out.println ("Video Format " + i + " : " + formats[i].getEncoding() + ", " + dim.width + " x " + dim.height );
    else
    System.out.println ("Error : No web cam detected");
    * grabs a frame's buffer from the web cam / device
    * @returns A frames buffer
    public Buffer grabFrameBuffer ( )
    if ( player != null )
    FrameGrabbingControl fgc = (FrameGrabbingControl)player.getControl ( "javax.media.control.FrameGrabbingControl" );
    if ( fgc != null )
    return ( fgc.grabFrame() );
    else
    System.err.println ("Error : FrameGrabbingControl is null");
    return ( null );
    else
    System.err.println ("Error : Player is null");
    return ( null );
    * grabs a frame's buffer, as an image, from the web cam / device
    * @returns A frames buffer as an image
    public Image grabFrameImage ( )
    Buffer buffer = grabFrameBuffer();
    if ( buffer != null )
    // Convert it to an image
    BufferToImage btoi = new BufferToImage ( (VideoFormat)buffer.getFormat() );
    if ( btoi != null )
    Image image = btoi.createImage ( buffer );
    if ( image != null )
    return ( image );
    else
    System.err.println ("Error : BufferToImage cannot convert buffer");
    return ( null );
    else
    System.err.println ("Error : cannot create BufferToImage instance");
    return ( null );
    else
    System.out.println ("Error : Buffer grabbed is null");
    return ( null );
    * Closes and cleans up the player
    public void playerClose ( )
    if ( player != null )
    player.close();
    player.deallocate();
    player = null;
    public void windowClosing ( WindowEvent e )
    playerClose();
    System.exit ( 1 );
    public void componentResized ( ComponentEvent e )
    Dimension dim = getSize();
    boolean mustResize = false;
    if ( dim.width < MIN_WIDTH )
    dim.width = MIN_WIDTH;
    mustResize = true;
    if ( dim.height < MIN_HEIGHT )
    dim.height = MIN_HEIGHT;
    mustResize = true;
    if ( mustResize )
    setSize ( dim );
    public void windowActivated ( WindowEvent e ) {   }
    public void windowClosed ( WindowEvent e ) {   }
    public void windowDeactivated ( WindowEvent e ) {   }
    public void windowDeiconified ( WindowEvent e ) {   }
    public void windowIconified ( WindowEvent e ) {   }
    public void windowOpened ( WindowEvent e ) {   }
    public void componentHidden(ComponentEvent e) {   }
    public void componentMoved(ComponentEvent e) {   }
    public void componentShown(ComponentEvent e) {   }
    protected void finalize ( ) throws Throwable
    playerClose();
    super.finalize();
    class MyToolBarAction extends AbstractAction
    public MyToolBarAction ( String name, String imagefile )
    // Note : Use version this if you supply your own toolbar icons
    // super ( name, new ImageIcon ( imagefile ) );
    super ( name );
    public void actionPerformed ( ActionEvent event )
    toolbarHandler ( this );
    class MyVideoFormat
    public VideoFormat format;
    public MyVideoFormat ( VideoFormat format )
    this.format = format;
    public String toString ( )
    Dimension dim = format.getSize();
    return ( format.getEncoding() + " [ " + dim.width + " x " + dim.height + " ]" );
    class MyCaptureDeviceInfo
    public CaptureDeviceInfo capDevInfo;
    public MyCaptureDeviceInfo ( CaptureDeviceInfo devInfo )
    capDevInfo = devInfo;
    public String toString ( )
    return ( capDevInfo.getName() );
    class MySnapshot extends JFrame implements ImageObserver
    protected Image photo = null;
    protected int shotNumber;
    public MySnapshot ( Image grabbedFrame, Dimension imageSize )
    super ( );
    shotNumber = shotCounter++;
    setTitle ( "Photo" + shotNumber );
    photo = grabbedFrame;
    setDefaultCloseOperation ( WindowConstants.DISPOSE_ON_CLOSE );
    int imageHeight = photo.getWidth ( this );
    int imageWidth = photo.getHeight ( this );
    setSize ( imageSize.width, imageSize.height );
    final FileDialog saveDialog = new FileDialog ( this, "Save JPEG", FileDialog.SAVE );
    final JFrame thisCopy = this;
    saveDialog.setFile ( "Photo" + shotNumber );
    addWindowListener ( new WindowAdapter()
    public void windowClosing ( WindowEvent e )
    saveDialog.show();
    String filename = saveDialog.getFile();
    if ( filename != null )
    if ( saveJPEG ( filename ) )
    JOptionPane.showMessageDialog ( thisCopy, "Saved " + filename );
    setVisible ( false );
    dispose();
    else
    JOptionPane.showMessageDialog ( thisCopy, "Error saving " + filename );
    else
    setVisible ( false );
    dispose();
    setVisible ( true );
    public void paint ( Graphics g )
    super.paint ( g );
    g.drawImage ( photo, 0, 0, getWidth(), getHeight(), Color.black, this );
    * Saves an image as a JPEG
    * @params the image to save
    * @params the filename to save the image as
    public boolean saveJPEG ( String filename )
    boolean saved = false;
    BufferedImage bi = new BufferedImage ( photo.getWidth(null),
    photo.getHeight(null),
    BufferedImage.TYPE_INT_RGB );
    Graphics2D g2 = bi.createGraphics();
    g2.drawImage ( photo, null, null );
    FileOutputStream out = null;
    try
    out = new FileOutputStream ( filename );
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder ( out );
    JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam ( bi );
    param.setQuality ( 1.0f, false ); // 100% high quality setting, no compression
    encoder.setJPEGEncodeParam ( param );
    encoder.encode ( bi );
    out.close();
    saved = true;
    catch ( Exception ex )
    System.out.println ("Error saving JPEG : " + ex.getMessage() );
    return ( saved );
    } // of MySnapshot
    public static void main (String[] args )
    try
    JWebCam myWebCam = new JWebCam ( "Web Cam Capture" );
    myWebCam.setVisible ( true );
    if ( !myWebCam.initialise() )
    System.out.println ("Web Cam not detected / initialised");
    catch ( Exception ex )
    ex.printStackTrace();

  • Which codec should I use for web cam capture?

    I've got my new Live! Cam Voice up and running with my PC. It captures audio and video fine but when I load the video into Adobe Premiere for further editting, Premiere doesn't seem to like the codec I'm using (WMV-Window Media Video). Inside Premiere the video does not seem to play at full frame rate and when I render out an export (to an QuickTime .mov for example) also seems to be having trouble converting the WMV input to that format or any format for that matter.
    Any suggestions? Thanks.
    Message Edited by Castaa on 07-16-2006 05:34 PM
    Message Edited by Castaa on 07-16-2006 05:36 PM

    solace wrote:
    Hi...
    Which recording quality setting was used? Best quality? or any of the preset options listed? Alternati'vely, you might want to try the I420 color format. This can be selected within movie maker.
    Hi,
    I'm capturing video using the Windows Media Video (.wmv) using the high quality setting (640x480). I think pixel capture problem I discribed above might be releated to hard drive access while the camera is capturing. Compression is set to I420. Same problem with the other option (RGB 24).
    Here is a picture my corruption problem:
    *** http://home.pacbell.net/jcortel/corruption.JPG ***
    This problem happens randomly about every minute (on average) of captured video and only for a frame. The discolored line appears at different heights in the frame and it sometimes thinker than this example.

  • Problem in  grabing images from two web cams

    Hi
    I am trying to modify single web cam capturing screen code into multiple web cam screen capturing. The method autoDetect() recognizes the web camera. I want to choose web cam by myself. I tried all devInfo from the list but it resulted no success. Always the first camera is selected . I use different cameras (Logitech and Genius). Please, how to detect both camera to work at the same time.
    public CaptureDeviceInfo autoDetect ( )
            Vector list = CaptureDeviceManager.getDeviceList (null);
            CaptureDeviceInfo devInfo = null;
                if ( list != null )
                String name;
                for ( int i=0; i<list.size(); i++ )
                    devInfo = (CaptureDeviceInfo)list.elementAt ( i );
                    name = devInfo.getName();
                   if ( name.startsWith ("vfw:") )
                                     break;
              ...The whole code is on: JWebCam

    Here's source code I posted to capture a frame from one webcam.
    http://forum.java.sun.com/thread.jspa?threadID=570463&tstart=25
    Lots of people have problems with multiple cameras, something to do with the
    Windows USB channels and failing to detect/select between the two.
    So, capturing frames from 1 web cam is relatively straightforward, but you may have serious problems with two or more.
    regards,
    Owen

  • Just today web-sites I frequent like reddit, oregonlive and even FB started taking forever to load. I've made no changes from yesterday and today. Any thoughts?

    Question
    Just today web-sites I frequent like reddit, oregonlive and even FB started taking forever to load. I've made no changes from yesterday and today. Any thoughts? edit

    asdfjava-er wrote:
    The book that I'm using said it wasn't necessary for this because it's supposed to just make sure everything is working properly--which it's not.OK, if you want to ignore my advice, so be it, but please don't complain that it is not going to work without even trying it yourself.
    asdfjava-er wrote:
    Now this is the part I don't get. The book tells me to go to http://localhost:8080/ch1/Serv1 even though there are no files/folders that have the name Serv1.
    Do you understand what the <servlet-mapping> declaration in the web.xml means? It is roughly just saying the appserver that it should port all requests on /Serv1 to the mentioned servlet.
    a couple others like/ch1/WEB-INF/classes/Ch1Servlet.class and /ch1/WEB-INF/web.xml. The WEB-INF folder is not public accessible, so forget about that part.
    "Resource not found" simply means that either the URL is wrong (case counts!) or that the resource is actually not there. I.e. not compiled, not deployed, not loaded, etcetera. Reading the appserver's startup logs might also help.

  • Capture Web Cam image in APEX and Upload into the Database

    Overview
    By using a flash object, you should be able to interface with a usb web cam connected to the client machine. Their are a couple of open source ones that I know about, but the one I chose to go with is by Taboca Labs and is called CamCanvas. This is released under the MIT license, and it is at version 0.2, so not very mature - but in saying that it seems to do the trick. The next part is to upload a snapshot into the database - in this particular implementation, it is achieved by taking a snapshot, and putting that data into the canvas object. This is a new HTML5 element, so I am not certain what the IE support would be like. Once you have the image into the canvas, you can then use the provided function convertToDataURL() to convert the image into a Base64 encoded string, which you can then use to convert into to a BLOB. There is however one problem with the Base64 string - APEX has a limitation of 32k for and item value, so can't be submitted by normal means, and a workaround (AJAX) has to be implemented.
    Part 1. Capturing the Image from the Flash Object into the Canvas element
    Set up the Page
    Required Files
    Download the tarball of the webcam library from: https://github.com/taboca/CamCanvas-API-/tarball/master
    Upload the necessary components to your application. (The flash swf file can be got from one of the samples in the Samples folder. In the root of the tarball, there is actually a swf file, but this seems to be a different file than of what is in the samples - so I just stick with the one from the samples)
    Page Body
    Create a HTML region, and add the following:
        <div class="container">
           <object  id="iembedflash" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
    codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" width="320" height="240">
                <param name="movie" value="#APP_IMAGES#camcanvas.swf" />
                <param name="quality" value="high" />
              <param name="allowScriptAccess" value="always" />
                <embed  allowScriptAccess="always"  id="embedflash" src="#APP_IMAGES#camcanvas.swf" quality="high" width="320" height="240"
    type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" mayscript="true"  />
        </object>
        </div>
    <p><a href="javascript:captureToCanvas()">Capture</a></p>
    <canvas style="border:1px solid yellow"  id="canvas" width="320" height="240"></canvas>That will create the webcam container, and an empty canvas element for the captured image to go into.
    Also, have a hidden unprotected page item to store the Base64 code into - I called mine P2_IMAGE_BASE64
    HTML Header and Body Attribute
    Add the Page HTML Body Attribute as:
    onload="init(320,240)"
    JavaScript
    Add the following in the Function and Global Variable Declarations for the page (mostly taken out of the samples provided)
    //Camera relations functions
    var gCtx = null;
    var gCanvas = null;
    var imageData = null;
    var ii=0;
    var jj=0;
    var c=0;
    function init(ww,hh){
         gCanvas = document.getElementById("canvas");
         var w = ww;
         var h = hh;
         gCanvas.style.width = w + "px";
         gCanvas.style.height = h + "px";
         gCanvas.width = w;
         gCanvas.height = h;
         gCtx = gCanvas.getContext("2d");
         gCtx.clearRect(0, 0, w, h);
         imageData = gCtx.getImageData( 0,0,320,240);
    function passLine(stringPixels) {
         //a = (intVal >> 24) & 0xff;
         var coll = stringPixels.split("-");
         for(var i=0;i<320;i++) {
              var intVal = parseInt(coll);
              r = (intVal >> 16) & 0xff;
              g = (intVal >> 8) & 0xff;
              b = (intVal ) & 0xff;
              imageData.data[c+0]=r;
              imageData.data[c+1]=g;
              imageData.data[c+2]=b;
              imageData.data[c+3]=255;
              c+=4;
         if(c>=320*240*4) {
              c=0;
              gCtx.putImageData(imageData, 0,0);
    function captureToCanvas() {
         flash = document.getElementById("embedflash");
         flash.ccCapture();
         var canvEle = document.getElementById('canvas');
         $s('P2_IMAGE_BASE64', canvEle.toDataURL());//Assumes hidden item name is P2_IMAGE_BASE64
         clob_Submit();//this is a part of part (AJAX submit value to a collection) two
    }In the footer region of the page (which is just a loading image to show whilst the data is being submitted to the collection [hidden by default]) :<img src="#IMAGE_PREFIX#processing3.gif" id="AjaxLoading"
    style="display:none;position:absolute;left:45%;top:45%;padding:10px;border:2px solid black;background:#FFF;" />If you give it a quick test, you should be able to see the webcam feed and capture it into the canvas element by clicking the capture link, in between the two elements - it might through a JS error since the clob_Submit() function does not exist yet.
    *Part 2. Upload the image into the Database*
    As mentioned in the overview, the main limitation is that APEX can't submit values larger than 32k, which I hope the APEX development team will be fixing this limitation in a future release, the workaround isn't really good from a maintainability perspective.
    In the sample applications, there is one that demonstrates saving values to the database that are over 32k, which uses an AJAX technique: see http://www.oracle.com/technetwork/developer-tools/apex/application-express/packaged-apps-090453.html#LARGE.
    *Required Files*
    From the sample application, there is a script you need to upload, and reference in your page. So you can either install the sample application I linked to, or grab the script from the demonstration I have provided - its called apex_save_large.js.
    *Create a New Page*
    Create a page to Post the large value to (I created mine as 1000), and create the following process, with the condition that Request = SAVE. (All this is in the sample application for saving large values).declare
         l_code clob := empty_clob;
    begin
         dbms_lob.createtemporary( l_code, false, dbms_lob.SESSION );
         for i in 1..wwv_flow.g_f01.count loop
              dbms_lob.writeappend(l_code,length(wwv_flow.g_f01(i)),wwv_flow.g_f01(i));
         end loop;
         apex_collection.create_or_truncate_collection(p_collection_name => wc_pkg_globals.g_base64_collection);
         apex_collection.add_member(p_collection_name => wc_pkg_globals.g_base64_collection,p_clob001 => l_code);
         htmldb_application.g_unrecoverable_error := TRUE;
    end;I also created a package for storing the collection name, which is referred to in the process, for the collection name:create or replace
    package
    wc_pkg_globals
    as
    g_base64_collection constant varchar2(40) := 'BASE64_IMAGE';
    end wc_pkg_globals;That is all that needs to be done for page 1000. You don't use this for anything else, *so go back to edit the camera page*.
    *Modify the Function and Global Variable Declarations* (to be able to submit large values.)
    The below again assumes the item that you want to submit has an item name of 'P2_IMAGE_BASE64', the condition of the process on the POST page is request = SAVE, and the post page is page 1000. This has been taken srtaight from the sample application for saving large values.//32K Limit workaround functions
    function clob_Submit(){
              $x_Show('AjaxLoading')
              $a_PostClob('P2_IMAGE_BASE64','SAVE','1000',clob_SubmitReturn);
    function clob_SubmitReturn(){
              if(p.readyState == 4){
                             $x_Hide('AjaxLoading');
                             $x('P2_IMAGE_BASE64').value = '';
              }else{return false;}
    function doSubmit(r){
    $x('P2_IMAGE_BASE64').value = ''
         flowSelectAll();
         document.wwv_flow.p_request.value = r;
         document.wwv_flow.submit();
    }Also, reference the script that the above code makes use of, in the page header<script type="text/javascript" src="#WORKSPACE_IMAGES#apex_save_large.js"></script>Assuming the script is located in workspace images, and not associated to a specific app. Other wise reference #APP_IMAGES#
    *Set up the table to store the images*CREATE TABLE "WC_SNAPSHOT"
    "WC_SNAPSHOT_ID" NUMBER NOT NULL ENABLE,
    "BINARY" BLOB,
    CONSTRAINT "WC_SNAPSHOT_PK" PRIMARY KEY ("WC_SNAPSHOT_ID")
    create sequence seq_wc_snapshot start with 1 increment by 1;
    CREATE OR REPLACE TRIGGER "BI_WC_SNAPSHOT" BEFORE
    INSERT ON WC_SNAPSHOT FOR EACH ROW BEGIN
    SELECT seq_wc_snapshot.nextval INTO :NEW.wc_snapshot_id FROM dual;
    END;
    Then finally, create a page process to save the image:declare
    v_image_input CLOB;
    v_image_output BLOB;
    v_buffer NUMBER := 64;
    v_start_index NUMBER := 1;
    v_raw_temp raw(64);
    begin
    --discard the bit of the string we dont need
    select substr(clob001, instr(clob001, ',')+1, length(clob001)) into v_image_input
    from apex_collections
    where collection_name = wc_pkg_globals.g_base64_collection;
    dbms_lob.createtemporary(v_image_output, true);
    for i in 1..ceil(dbms_lob.getlength(v_image_input)/v_buffer) loop
    v_raw_temp := utl_encode.base64_decode(utl_raw.cast_to_raw(dbms_lob.substr(v_image_input, v_buffer, v_start_index)));
    dbms_lob.writeappend(v_image_output, utl_raw.length(v_raw_temp),v_raw_temp);
    v_start_index := v_start_index + v_buffer;
    end loop;
    insert into WC_SNAPSHOT (binary) values (v_image_output); commit;
    end;Create a save button - add some sort of validation to make sure the hidden item has a value (i.e. image has been captured). Make the above conditional for request = button name so it only runs when you click Save (you probably want to disable this button until the data has been completely submitted to the collection - I haven't done this in the demonstration).
    Voila, you should have now be able to capture the image from a webcam. Take a look at the samples from the CamCanvas API for extra effects if you wanted to do something special.
    And of course, all the above assumed you want a resolution of 320 x 240 for the image.
    Disclaimer: At time of writing, this worked with a logitech something or rather webcam, and is completely untested on IE.
    Check out a demo: http://apex.oracle.com/pls/apex/f?p=trents_demos:webcam_i (my image is a bit blocky, but i think its just my webcam. I've seen others that are much more crisp using this) Also, just be sure to wait for the progress bar to dissappear before clicking Save.
    Feedback welcomed.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    Hmm, maybe for some reason you aren't getting the base64 version of the saved image? Is the collection getting the full base64 string? Seems like its not getting any if its no data found.
    The javascript console is your friend.
    Also, in the example i used an extra page, from what one of the examples on apex packages apps had. But since then, I found this post by Carl: http://carlback.blogspot.com/2008/04/new-stuff-4-over-head-with-clob.html - I would use this technique for submitting the clob, over what I have done - as its less hacky. Just sayin.

  • Capture an image using the web camera from a web application

    Hi All,
    Could anyone please share the steps what have to be followed for capture an image using the web camera from a web application.
    I have a similar requirement like this,
    1) Detect the Webcam on the users machine from the web application.(To be more clear when the user clicks on 'Add Photo' tool from the web application)
    2) When the user confirms to save, save the Image in users machine at some temporary location with some unique file name.
    3) Upload the Image to the server from the temporary location.
    Please share the details like, what can be used and how it can be used etc...
    Thanks,
    Suman

    1) Detect the Webcam on the users machine from the web application.(To be more clear when the user clicks on 'Add Photo' tool from the web application)There's not really any good way to do this with JMF. You'd have to somehow create a JMF web-start application that will install the native JMF binaries, and then kick off the capture device scanning code from the application, and then scan through the list of devices found to get the MediaLocator of the web cam.
    2) When the user confirms to save, save the Image in users machine at some temporary location with some unique file name.You'd probably be displaying a "preview" window and then you'd just want to capture the image. There are a handful of ways you could capture the image, but it really depends on your situation.
    3) Upload the Image to the server from the temporary location.You can find out how to do this on google.
    All things told, this application is probably more suited to be a FMJ (Freedom for Media in Java) application than a JMF application. JMF relies on native code to capture from the web cams, whereas FMJ does not.
    Alternately, you might want to look into Adobe Flex for this particular application.

  • Change the video resolution when capturing a WEB-cameras

    Language: Java
    It is used in addition: JMF
    When capturing video from WEB-cameras with JMF - getting the video is at the lowest resolution.
    Can you please tell how to change the video resolution?
    The code by which the captured image (no SWING-forms):
    MediaLocator getWebCam = new MediaLocator("vfw://0");
    private Player player;
    Timer timer = new Timer(40, this);
    public BufferedImage grabFrameImage() {
    Image image = null;
    FrameGrabbingControl frameGrabbingControl = null;
    if (player != null)
    frameGrabbingControl = (FrameGrabbingControl) player.getControl("javax.media.control.FrameGrabbingControl");
    Buffer buffer = frameGrabbingControl.grabFrame();
    if (buffer != null)
    image = new BufferToImage((VideoFormat) buffer.getFormat()).createImage(buffer);
    if (image != null)
    return (BufferedImage) image;
    return null;
    public WorkWithWebCam() throws NoDataSourceException, IOException, NoPlayerException {
    initComponents();
    player = Manager.createPlayer(Manager.createDataSource(getWebCam));
    player.start();
    private void jButton1ActionPerformed(ActionEvent e) {
    timer.start();
    public static void main(String args[]) {
    EventQueue.invokeLater(new Runnable() {
    public void run() {
    try{
    new WorkWithWebCam().setVisible(true);
    }catch(Exception ex){}
    public void actionPerformed(ActionEvent e) {
    panelMain.getGraphics().drawImage(this.grabFrameImage(), 0, 0, 400, 300, null);
    P.S. Can you please tell how this forum can be identified code \ listing?

    Hello,
    I don't know if there is a way to change the video. But I think you can easily use your own videos by using a local .mpg or .3gp file via InputStream. Just change the player's parameters in video/mpg instead of capture://video.
    Hope it helps...
    Torsten

  • Capturing images from two web camera in real time

    Hi,
    I need to compare two pictures from two webcameras. I will make some easy computing on them, so there should be no speed problem, but i dont know how can i take each picture? is there any action which is called each time a frame comes? do sb have some sample code?
    thanks
    JJ

    Here's source code I posted to capture a frame from one webcam.
    http://forum.java.sun.com/thread.jspa?threadID=570463&tstart=25
    Lots of people have problems with multiple cameras, something to do with the
    Windows USB channels and failing to detect/select between the two.
    So, capturing frames from 1 web cam is relatively straightforward, but you may have serious problems with two or more.
    regards,
    Owen

  • Satellite L300-256 - web cam isn't working - Just show Black Colour.

    Hello,
    i use Toshiba L300-256 model laptop and my web cam was working before some months and today i opened it and it seems to be stopped working.
    Its CHICONY USB 2.0 webcam
    At first it shows that "some application prevent its working". So i uninstalled all newly installed programs. Then also my webcam didnt work. So i unistalled the driver and installed it again from the driver file downloaded from here. Then also my problem didnt fixed. It just show dark background in the place where image will come while capturing.
    Camera blue light is appearing but there isnt any picture coming, eventhough i am in a bright lighted room.
    Please help me to fix this issue.
    Thanks

    Hi
    Do you use face recognition utility?
    This software locks and use the webcam too
    Maybe there is something wrong between these both tools
    In your case I recommend uninstalling the face recognition and webcam software.
    Clean the registry using CCLeaner (freeware).
    Then reboot twice and start with webcam installation then check if the webcam would works

  • I just purchased a camera packaged with Adobe photoshop Elements 11. I have a mac book air- which does not have a cd drive. The package did not come with a code or anything that would provide me with another way to install photoshop that came with my came

    I just purchased a camera packaged with Adobe photoshop Elements 11. I have a mac book air- which does not have a cd drive. The package did not come with a code or anything that would provide me with another way to install photoshop that came with my camera. Is there any other way i can install this on my camera without using the provided cd or buying the software again?

    That doesn't help the user with the serial code though.
    There has to be some kind of code somewhere within the package. The disk itself does not contain one. You can look here for help with finding your serial number:
    Find your serial number quickly

  • Web cam code clarification

    Hi
    Saw this code listed on another site
    <img
    height=310 alt="Plymouth Webcam"
    src="C-Cheeta%20WEATHER_files/plymouth.jpg" width=412
    border=2><BR>
    I'm assuming that this "web cam image" is simply a jpeg that
    is refreshed at
    a specific time interval??
    If so any idea where I can source the refresh javascript?
    thanks
    Ian

    Hi
    thanks for that, I begin to see the light at the ned of the
    tunnel:-) was
    underthe missaprehension that it wqs video- silly me
    cheers
    Ian
    "Ken Binney" <[email protected]> wrote
    in message
    news:g6t3v6$j0b$[email protected]..
    > <meta HTTP-EQUIV="imagetoolbar" and CONTENT="no">
    > <META HTTP-EQUIV="Refresh" CONTENT="10">
    > </head>
    >
    >
    >
    http://www.bbc.co.uk/england/webcams/live/plymouth.jpg
    >
    >
    >
    > "Ian Edwards"
    <[email protected]> wrote in message
    > news:g6stnr$chr$[email protected]..
    >> Hi
    >>
    >> Saw this code listed on another site
    >>
    >> <img
    >> height=310 alt="Plymouth Webcam"
    >> src="C-Cheeta%20WEATHER_files/plymouth.jpg"
    width=412
    >> border=2><BR>
    >>
    >> I'm assuming that this "web cam image" is simply a
    jpeg that is refreshed
    >> at a specific time interval??
    >>
    >> If so any idea where I can source the refresh
    javascript?
    >>
    >> thanks
    >>
    >> Ian
    >
    >

  • 2 Web camera interface and capture in labview

    Dear Friends,
    I am trying to capture images with 2 USB cameras (HP web camera) located at 2 different positions. But i could connect 1 camera only, even that picture also clear. I could not do any camera setting.Can anyone help me...... 
    Thanks,
    Klattan

    Hi Klattan,
    see this link:
    http://forums.ni.com/ni/board/message?board.id=170​&message.id=382013&query.id=370045#M382013  
    With some transformation you anyhow should be able to work with the IMAQ functions.
    Hope it helps.
    Mike

  • Question about a camera/web​-cam

    Hi,
    Does best buy sell any camera/web-cam/security camera that can record to your computer or phone so you can watch it in the morning?
    I want to see what my cats are up to during the night when I wake up, if they are being naughty or nice.
    Preferably something not that expensive.
    A motion sensored one would be good also if they sell any of those.
    Ty.

    Hmm....
    check out this video where VLC uses your webcam to record
    http://www.youtube.com/watch?v=5Z5c28rd5Wk
    Yes, Best Buy has security cameras.  Do your research to see if they meet your needs
    http://www.bestbuy.com/site/home-security-safety/h​ome-surveillance-cameras/pcmcat254000050005.c?id=p​...
    check Google Play or iTunes store for possible phone apps. 
    Will the room be well lit, or totally dark?  Many cameras don't work well in the dark.  The better ones have an IR or illumination light.  In extreme low light, this is my fav camera that records with minimal light assistance.  The video is stored on an SD card that you can load onto your computer.
    http://www.bestbuy.com/site/tlc200-f1-2-time-lapse​-and-stop-motion-hd-video-camera-built-in-super-wi​...
    GoPro's also have an ability to store video for around an hour.
    It's amazing the wild naked animal action cameras will capture when you are not around.
    http://www.youtube.com/watch?v=SXVkCkXf5LA
    http://www.youtube.com/watch?v=-xa0JLPgiPA
    http://www.youtube.com/watch?v=DT4ikdAS-P0
    http://www.youtube.com/watch?v=rPZNjtODzFI

  • Capture a photo or video through my web cam

    Greeting for the day to every one !!
    I am trying to provide a facility in my project that any one capture his photo or video through web cam in their own computer. Is it possible in oracle /d2k ?? if yes please help me regarding this. How can i invoke my web cam through oracle/d2k and capture the photo.
    Any one help me ..
    Avinash Pandey

    You will have to free some space up on your iPhone. Buying more iCloud storage will not increase the capacity of your iPhone. For the most part iCloud storage is for your iOS backups, documents such as iWork files and iCloud email. Aside from iTunes Match and PhotoStreams which do not count towards iCloud storage you can not store media files on iCloud. PhotoStream is not a photo backup service nor does it support video yet, it's intended use is for sharing and transferring photos to other devices.
    Not sure of your setup but chances are you have a lot of video and photos on your iPhone taking up your storage space. These should be copied over to a computer where they can be properly backed up and organize. Once organized you can transfer them back to the iPhone through iTunes. You can sync a smaller number to free space. Or since you have a copy on the computer it is now possible to delete the photos from your iPhone when have the need to make a new video. Settings/General/Usage/Photos & Camera then swipe sideways to reveal the delete button is a quick way to delete photos in the library when you need more space. Ensure you still have a backup on a PC and an external drive.

Maybe you are looking for

  • Asset Gl balances are not matching with Asset history

    Hi Gurus, I run the ABST2 transaction it is giving the error message . Company code Asset balance sheet values are not completely posted Message no. MQ554 Diagnosis The asset balance sheet values in Financial Accounting are not posted all depreciatio

  • Is it better to store the image in the database or to use BFile

    Hi all, I've a doubt regarding the handling of the image. For example i've the images of the persons amounting to 50,000(the number will be increased in future). So i just want to know which is the better menthod. is it better to store all the images

  • Acrobat 9-Possible to Crop to TrimBox?

    Hello, I have a feeling this is very easy to do. I am not familiar with any acrobat scripting. Where's the object model viewer? How do you add the script?(I hate this question) I know I can figure it out with a little research. Any help would be a ve

  • Have to double tap screen to open anything and can't scroll up/down

    I have to dbl tap screen to open anything and can't scroll up or down. When I toucj once it puts a box around icon.

  • SSLEXT With Struts 1.1. and Tiles

    Struts 1.1 (with tiles) Java 1.5 Tomcat 5.5.9 MySQL 5.0 I have downloaded the sslext.jar from sourcefourge, in an attempt to implement transparent switching betweek http and https action mappings. I have followed the implementation guide here http://