Video camera capture/streaming: example implementation
If anyone is interested I have put together a very simple video capture app using LTI-CIVIL (an open source video streaming library for Java) and using JavaFX. This is a more complete/useful example of some code I posted months ago doing something similar.
Performance and reliability seems to be reasonable but I have not tested heavily.
The code (ANT build included) can be found at: http://code.google.com/p/jfxcamera/source/browse/trunk/
The code is simple (one class only) and intended to be demonstration so you can copy/paste and hack at to get it into your own project if you want. Note that the LTI-CIVIL project is nothing to do with me, I've just integrated it. If you find this at all useful thank whoever made LTI-CIVIL - my effort was trivial.
According to the website LTI-CIVIL supports the big 3 OS's but I have only tested it on Windows (only runs on a 32 bit windows JVM, there is no 64bit version of LTI-CIVIL). The code should be the same however.
http://lti-civil.org/
I realise this is hardly the full/proper support for media capture that this request is asking for but if you're really needing something while the JFX guys are working on a more integrated solution, this could be your answer.
Questions/problems: reply to this thread and I will try and answer.
This gives some useful info on the Lumia Video Camera
http://allaboutwindowsphone.com/reviews/item/13757_Nokia_Lumia_800-Part_2b-Camcor.php
If I have helped at all, a click on the White Star is always appreciated :
you can also help others by marking 'accept as solution'
Similar Messages
-
How to transmit both screengrabber stream and camera capture stream
hello, everyone
i am a student
i wonder how can i transmit both of the creengrabber stream and camera capture stream at the same time
hope that you can give me some suggestionshmm... intersting...
seems that you'll need to somehow mix two streams together.
1. I dont know how mixing works, so mabe someone else might be able to help you (however, you can still look into merging 2 video data sources, as in Manager.createMergingDataSource() )
2. You can transmit 2 streams to 2 different multicast addresses, which is definitely easier, than mixing
3. Careful with multicast, because it's probably working only within your campus area, but not beyond. I was unfortunate to almost fail my project because i used muticast for video streaming, which of course didnt work on public internet.
I hope someone else can give some ideas, plz. -
N97 Video camera captures Blurred (Un-Focused) Vid...
Hello,
I have recently found out that my phone cant focus at all .. Using image mod, the camera manages to auto-focus and the images are amazing, but when it comes to video, its blurred !!
For example, if I hold the camera 25cm above a paper, it wont pick up any words, it will only capture black lines
The sentences are all blurred out.
If I take a video footage of a friend that is 1m away, the details are better BUT are still blurred
Now the N97 has 5mega pixels and the N95 has 5mp as well, but my N95 captures sharp videos
Can someone tell me how can I fix this issue ????
Kind Regards,
ZAdded to the above :
I have also noticed that when video recording, the audio keeps changing its volume !!! For example : I stand 2m away from the phone while its recording, and make a contineuous sound, the sound's volume increases and then suddenly dicreases so much that I can barely hear it
After that, the volume increases again and the loop is reset.
WHYYYY is that happening ? Is it a hardware error ? or is it a software problem ?
I have installed v2.0 after a hard-reset today hoping that it will fix it..but it didnt
Please help !!!!! -
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(); -
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(); -
Capture stream from camera in JSF ADF
Hello to everyone,
I have a strange question. Is there any solution if I want to capture stream from camera in my jspx page. I've searched in the net but unfortunately i haven't found anything.
So, if somebody knows how this problem could be implement I will be very grateful.
Thanks in advance,
RegardsSaykov,
Nothing really to do with jsp/jspx whatsoever. You see, jsp runs on the server. The camera is connected to the client. You would need some type of Java applet/ActiveX/flash object (e.g., something running on the client, where the camera is) to do this. I do know that Flash is able to connect to locally attached cameras (I have seen Flash-based web conferencing software that is able to stream presentations via a webcam)
John -
How do I route audio from a YouTube video to AU Lab using SoundFlower so that I can capture the YouTube video's sound stream?
Attach camera via USB or put card in card reader.
Go to FCP, and go to the Log and TRANSFER window.
If FCP recognizes the card, you will see your clips listed on the left.
You can view them, set Ins and Outs, and import just what you want.
Once you choose a section of video and import it, FCP converts (transcodes) from its original camera format to Apple ProRes422 - a more edit friendly video file. -
FCE: Possible to Capture SD footage from digital video cam?
Ok, probably a daft question this. Don't laugh...
I'm thinking of purchasing a digital video camera that uses SD cards. I currently use a MiniDV cam and connect via Firewire.
Is it possible to capture footage shot on SD cards into FCE?
And, if so, should I use USB from the camera, or insert the SD card into my card-reader?
The camera I'm looking at is able to record HD footage to a 2gb SD card (about 40 mins worth)
Thanks for your time!Cheers Tom, I think you just saved me a small fortune..
Here's the camera: http://reviews.cnet.co.uk/camcorders/0,39029967,49263047,00.htm
(is it ok to link outside of the forums?)
In case the link get removed by a moderator, the model is the Sanyo VPC-HD1 -
Hello,
I am a teacher and want to make some videos to post online for my class. I would like to have it set up so that I have a powerpoint presentation going, a video camera pointing at a piece of paper I can write on and another video camera pointing at me. How do I do this? I have seen several solutions but they seem to be for switching between videos whereas I want both video images to be on at the same time.
Also, is there a screen capture program you would recommend?Go to System Preferences - Sharing and change the computer name there. You can also, optionally, change the name of your hard drive to further clarify the origin of your backups. Click once on the "Macintosh HD" on your desktop, then click its name to allow you to edit it.
Matt -
Can't capture from my cannon video camera to Final Cut or iMovie.
Hi. I can't capture from my cannon video camera to FInal Cut or iMovie. ANy help would be greatly appreciated. I don't think my iMac is recognizing the camera. I was told I don't need a firewire, that USB would work if I'm just capturing. If I need a firewire what kind (the one I was sold didn't fit). I'm getting an "unable to locate external device message". Not sure of next steps to try. Thanks.
Computer= iMac 21.5-inch: 2.5GHz
2.5GHzQuad-Core Intel Core i5
1920 x 1080resolution
4GB (two 2GB)memory
500GB harddrive1
AMDRadeon HD 6750M with 512MB
Processorand Memory -
Powered by a quad-core Intel Core i5 or i7 processor and DDR3memory.
Connectionsand Expansion
SuperDrive, SDXC card slot, audio in, audio out, USB 2.0,FireWire 800, Thunderbolt, Gigabit Ethernet.
Video camera = Canon Vixia HV40
Standard Definition or High Definition
High Definition
Power Consumption
4.3 W
Television System
NTSC
Video Recording system
MPEG2
Image Sensor
1/2.7-inch CMOS, RGB Primary Color Filter
Total Pixels
Approx. 2.96 Megapixels
Effective Pixels
Tape: HD/DV (16:9) mode: Approx 2.07 Megapixels (1920x1080) DV (4:3) mode: Approx 1.55 Megapixels (1440 x 1080) Card: (16:9) mode: Approx. 2.07 Megapixels (1920 x 1080), (4:3) mode: Approx. 2.76 Megapixels (1440 x 1080)
Tape Format
HDV / DV
Maximum recording Time
SP: 80 minutes, HDV, DV LP: 120 minutes DV
Lens
Zoom Ratio 10x Optical / 200x Digital Focal Length f=6.1-61mm (35mm equivalent: 43.6 - 436mm) Zoom Speed Variable / 3 Fixed Zoom Speeds Max. F/Stop f/1.8-3.0mm (when tapes are used)
Focusing System
Instant AF, TTL (through the lens)
Manual Exposure
Yes
Programmed AE
Auto, Program, Av, Tv, CINE, Portrait, Sports, Night, Snow, Beach, Sunset, Spotlight, Fireworks
Max Shutter Speed
Movie: 1/2000, Still image: 1/500
Auto Date/Time
Yes
Record Search/Review
Yes
Focusing System
10 mm (wide) / 1m (tele)
White Balance
Auto, Daylight, Shade, Cloudy, Tungsten, Fluorescent, Fluorescent H, Manual
Frame Rate
60i, Native 24p Progressive (records at 24p), 24p Progressive (records at 60i), 30p Progressive (records at 60i)
Minimum Illumination
0.2 lx (Night Mode)
Image Stabilization
SuperRange Optical (lens shift)
Filter Diameter
43mm
Viewfinder
Widescreen 0.27-inch Color Viewfinder / (Approx. 123,000 dots)
LCD Screen
2.7-inch Widescreen LCD (Approx. 211,000 dots)
Recording Media
High Definition Mini DV (recommended) (63 min) or MiniDV cassette
USB Terminal
USB 2.0 Full Speed
Video Terminal
component (output), composite (output)
Audio
DV: 16 bit (2ch) 48 kHz 12 bit (4ch) 32 kHz 4ch synchronous recording not possible HDV: MPEG1 Audio Layer II (2 ch) (4-channel playback of tapes containing 4-channel recordings possible)
Accessory Shoe
Advanced
Supplied Video Editing Software
None
HDMI Terminal
HDMI Type A (19 pins) Connector (output)
Microphone Terminal
3.5 mm stereo mini-jack
AV Mini Terminal/Headphone Terminal
3.5 mm 4 pole mini-jack (video/audio input and output)
Dimensions
(W X H X D) 3.5 x 3.2 x 5.4 in. (88 x 82 x 138mm)
Weight (not including lens and battery pack)
1.2 lbs. (535g)
Weight
1.4 lbs. (615g)Forget USB for capturing from tape. USB is only for stills from a Tape Based camera.
You require a firewire cable.
The camera connection end will be four pin and the Mac is nine pin to the 800 port.
Ask for a 9 to 4 pin firewire cable. Sounds like you have the wrong one as they can also be 4 to 4 or 4 to 6 pin!!
Also you will need the correct Easy Setup in FCE so FCE talk to the camera, exactly which one depends on what type of footage is being sent to FCE from the camera during capture.
Al -
How can I download video from a Canon ZR30 video camera to my IMac? I have Elgato Video Capture, but the provided connectors are loose in the camera and the camera does not have a white female end. No signal shows up on the computer when I connect the red and yellow connectors.
Broken solder joints on the camera me thinks!!
sorry -
Video capture from video camera to macbook
I can't figure out how to capture my video off my video camera and transfer it to my macbook. I have QT pro and have attached the firewire, but when QT pro launches, there is no option to capture...any thoughts? Thanks
File, New Movie Recording. Press red button.
-
Capture using software Video Camera
Hello,
I want to record screeb actions and insert them in my webhelp
project. These are the steps I followed:
1. Double click on the software video camera tool
The software video camera opens
2. Define the capture area
The help instructs that I should click on the "Record" button
once this has been done. However the Record and Stop button appear
dimmed and Iam unable to take the screen captures. am I missing
something?
Thanks
CP.Hi CP
I stand to be corrected, but I believe that little tool can't
handle the newer screen color depths. I think the tool came about
back when it was a luxury for some to have a display that was
capable of running 256 colors. So it expects a maximum of 256
colors.
You should probably investigate Adobe Captivate for this
purpose.
Cheers... Rick -
Hello, wonder if I can edit movies in iMovie with other cameras. For example: A camera of another brand, passing it to my PC and I could play in iPadm doing editing videos? thank you
Not sure what you mean. You can import video into I Movie either via your USB slot if it is already in digital format or via your fire wire slot (you may need an adapter as the MAC slot is a mini slot, the adapters are available on line) if you are coming from tape based media.
-
Intermittant problems recognizing my Sony video camera when capturing
When filming live, I have an intermittant problem with PPro 6 recognizing my Sony video camera when capturing. I hit the G (for start recording) and something it goes live and sometime the capture window goes to digital mess. I am using the "no" device control preference setting as I was told to by the Sony customer care tech.
Has anyone had a similar problem?You might provide more information about your setup... PPro Information FAQ http://forums.adobe.com/message/4200840
If Windows, are you using the legacy Firewire driver?
http://helpx.adobe.com/premiere-pro/kb/cant-capture-dv-hdv-video.html
-and Windows http://forums.adobe.com/message/4708997
Maybe you are looking for
-
How to get How do I get my Vista PC to See my Photosmart 5515 Printer via my wireless network
I have recently purchased a Photosmart 5515 (B111h) printer and have followed the setup instructions to the letter. The printer is now connected to the wireless network with an IP address of 192.168.0.4. Nomatter what I try I cannot get my PC or lapt
-
Displaying an ArrayList of values in JSP
Hi , I have a servlet called Submit Servlet that basically gets a EmpID from the request parameter , searches in a LetterRequest Table and sets matching records in an ArrayList of objects My probelm is sending this ArrayList to a JSP and displaying a
-
Play DVD on iMac and watch it on TV
I don't have a DVD player with my television. If I want to watch DVD movies on my TV screen, can I do this by connecting my iMac -- which plays DVDs -- to my television? Is this where I would need the Apple Video Adapter? According to the iMac manual
-
Resolution/Aspect Ratio of .SWF
hi all, i just need to know how the aspect ratio of swf be same when we play the swf on LCD,Plasma TVs. As currently the .swf changes if we check it on the TV screen. Any help on this will be highly appriciated. thanks and regards nik
-
CRM2007 UI - Problem with interface loading when i select a business role
Hi, When i run the t.code:BSP_WD_CMPWB and choose component:CRM_UI_FRAME and i logon to the web application server , i see all the Business roles but however when i select any of the roles i just see a blank page. Need help ASAP. Points would be giv