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();

Similar Messages

  • 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();

  • 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.

  • HP Truevision HD web cam no longer working with Skype since windows 8.1 update

    Hi guys,
                     A major annoying problem as occured since i updated to windows 8.1 my web cam no longer works in skype, it works for everything elese youcam etc just not skpye, audio is working fine too. When i go into settings the programmes freezes and eventually crashes, I can see my webcam listed in skype but thats it, the bottom half of the pane is missing too it cuts out in the middle of clear history, rolled back the driver and it works but messes everything else up. Please help i am ripping my hair out..... thank you

    odizzle7,
    Welcome to the HP Forum.
    Skype does run on Windows 8.1, although you may need to update Skype to at least version 6.16.0.105
    If you have more issues, please do consider opening a New Post of your own.
    This Thread is from last year and is not monitored by our Experts team.
    Click the Kudos Thumbs-Up to show you appreciate the help and time from our Experts.
    Although I strive to reflect HP's best practices, I do not work for HP. 
    Click Accept as Solution when the Answer is a good Fix or Workaround!
    Kind Regards,
    Dragon-Fur

  • 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

  • After LION update web Cam is no longer being detected at all. Does anyone have a fix? Thank you

    After LION update web Cam is no longer being detected at all. Does anyone have a fix? Thank you

    Thank you, Rod!
    While researching frame rate I came across this helpful blog posting: Crazy about Captivate: Lessons Learned: Video and Resolution in Adobe Captivate
    This is the line that caught my attention: "I discovered, after several experiments, that if you publish a course in Captivate as SCALABLE with a video inserted, no matter what the resolution, it makes the video look pixelated."
    When I unclick the "scalable HTML content" button before publishing, the video is fine!
    Big sigh of relief! Now I just need to figure out why audio won't play on one of the slides (it has an accordian widget, if that's relevant) and why I can no longer use Effects (I get the message, "Effect file is not valid")

  • 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

  • My web cam is not working, I downloaded a update of the web cam it was a 15 day trial, I dec ided I

    I downloaded a updated version of the web cam installed on my laptop, it was a version 5, this is what I was told that would come with the laptop, is was a 15 day trial, I decided I didn't want to purchase it, and now my web cam is not working

    Hi, 
    You may have a virus on your PC.  Review this NBC Nightly news article.
    HP DV9700, t9300, Nvidia 8600, 4GB, Crucial C300 128GB SSD
    HP Photosmart Premium C309G, HP Photosmart 6520
    HP Touchpad, HP Chromebook 11
    Custom i7-4770k,Z-87, 8GB, Vertex 3 SSD, Samsung EVO SSD, Corsair HX650,GTX 760
    Custom i7-4790k,Z-97, 16GB, Vertex 3 SSD, Plextor M.2 SSD, Samsung EVO SSD, Corsair HX650, GTX 660TI
    Windows 7/8 UEFI/Legacy mode, MBR/GPT

  • Not rally a question, just wanted to share my absolute frustration with the update of iTunes...this is, without a shadow of a doubt THE WORST application i have EVER used, Mac or PC! And that's saying something with the amount of PC dross that's out there

    Not rally a question, just wanted to share my absolute frustration with the update of iTunes...this is, without a shadow of a doubt THE WORST application i have EVER used, Mac or PC! And that's saying something with the amount of PC dross that's out there...Apple...PLEASE update and give us back the old version of iTunes...

    Pull down View > Show Sidebar. This will give you back the same functionality of iTunes 10.x.x.

  • I have Photoshop CS 5.5 version, but I've just changed my camera and I can't open my raw files. I need for my new camera Photoshop CC and Camera Raw 8.7 version. How can I do to update the old version? Thank you

    I have Photoshop CS 5.5 version, but I've just changed my camera and I can't open my raw files. I need for my new camera Photoshop CC and Camera Raw 8.7 version. How can I do to update the old version? Thank you

    Thank you for your valuable advice. I've solved the problem right now.
    Thanks
    2015-03-16 15:06 GMT+01:00 c.pfaffenbichler <[email protected]>:
        I have Photoshop CS 5.5 version, but I've just changed my camera and
    I can't open my raw files. I need for my new camera Photoshop CC and Camera
    Raw 8.7 version. How can I do to update the old version? Thank you
    created by c.pfaffenbichler
    <https://forums.adobe.com/people/c.pfaffenbichler> in *Photoshop General
    Discussion* - View the full discussion
    <https://forums.adobe.com/message/7302535#7302535>

  • Only half of the body just below the camera and steel side of camera side is getting heated up just after 10 , 15 mins of usage i my iphone  4 is it normal...as earlier the body was not heating up even after 2 hours....the problem started after updating t

    only half of the body just below the camera and steel side of camera side is getting heated up just after 10 , 15 mins of usage i my iphone  4 is it normal...as earlier the body was not heating up even after 2 hours....the problem started after updating to 6.1.2
    iPhone 4, iOS 6.1.2

    Hi, did you ever solve this problem?
    My 1 year old -- ha! one month out of warranty -- iPhone 4 has been having a nearly identical problem over the past few days.
    It started by dying completely so I had the battery replaced, thinking it was simply battery issue.
    It then worked again for a moment but started doing exactly what you describe, going through a reset cycle (longer than 30 seconds but who's counting). And it felt quite warm.
    Did hard reset, plugged into wall charger and MBP USB but the new battery wouldn't even get a full charge (a whopping 92% after nearly two days). It would even lose battery when plugged in if I opened an app. And all the while plugged in, if I left the phone on, it would cycle through these resets. So I turned it off to try to charge it.
    Now suddenly, it's dead again. Totally black, and hard reset does nothing. Up until two days ago there was nothing wrong whatsoever with this phone! And I hadn't even installed a new app that could be the root of the issue. No idea whatsoever what caused this.
    Any help would be much appreciated!!

Maybe you are looking for

  • How to pass values to XML complex type of a Webservice using PL/SQL

    HI, I need to call a web service from PL/SQL that has an complex type element. That complex type element has 4 child elements each of integer type. I want to pass values for this complex type using SOAP_API.add_parameter but I can't understand how to

  • Populating Tree with External XML File

    I want to use external files for populating Flex 3 components. I have been successful using code very similar to that below for a data grid & for a combo box, but it won't work for a tree. Can you determine wh? <?xml version="1.0" encoding="utf-8"?>

  • Use G4 in a network

    I'm not sure where to post this. We have early model G4 466 Mhz that has factory CD & Zip drives original HD crashed several years ago and I exchanged it out for either 200 or 250 Gig HD, that shows up in profiler as 114 Gig & I think there is still

  • Oracle Licenses Info

    Hello All, I am having Oracle RAC 11gR2 on AIX 7.1, each node is 10 cores. I am planing to start implementing my DR site. I already have 20 licenses Oracle Database Enterprise Edition and 20 licenses Real Application clusters and 20 licences Oracle A

  • Bizarre file size saved after using Pen Selection Tool in CS4/3

    Bizarre file size after using and saving pen selection. Image file  size = 69.9mb at 300ppi for 14.2 x 9.5" image. If one crops the image about by hal and saves it, the file size = 34.2mb. If one uses the pen tool and selects the same area that was c