Download the latest JMF from sun and install it. Http://java.sun.com/products/java-media/jmf/index.jsp
Then, let's talk about the requirements.
1. Take a photo with a camera
2. Enter the file name in the text box.
3. Click the photo button to obtain the image in the camera.
4. A fixed size photo is taken in a red box.
5. Save the image as JPG and do not compress the image quality.
The key technology, I believe, is also the most interesting part, that is, how to get a camera to work and take a photo.
Using JMF, the code is simple:
// Use these three categories to obtain the camera driver and the image stream in the camera. The obtained image stream is a swing component class.
public static Player player = null; private CaptureDeviceInfo di = null; private MediaLocator ml = null; String str1 = "vfw:Logitech USB Video Camera:0"; String str2 = "vfw:Microsoft WDM Image Capture (Win32):0"; di = CaptureDeviceManager.getDevice(str2); ml = di.getLocator(); try { player = Manager.createRealizedPlayer(ml); player.start(); Component comp; if ((comp = player.getVisualComponent()) != null) { add(comp, BorderLayout.NORTH); } } catch (Exception e) { e.printStackTrace(); } |
Next, click to take a photo and get the current image in the camera.
The Code is also very simple:
Private jbutton capture; private buffer Buf = NULL; private buffertoimage btoi = NULL; private imagepanel imgpanel = NULL; private image IMG = NULL; private imagepanel imgpanel = NULL; jcomponent c = (jcomponent) e. getsource (); If (C = capture) // If you press the photo button {framegrabbingcontrol FGC = (framegrabbingcontrol) player. getcontrol ("javax. media. control. framegrabbingcontrol "); Buf = FGC. grabframe (); // obtain the current shard and store it in the buffer class btoi = new buffertoimage (videoformat) BUF. getformat (); IMG = btoi. createimage (BUF); // show the image imgpanel. setimage (IMG );} |
The following is the sample code.
Bufferedimage Bi = (bufferedimage) createimage (imgwidth, imgheight); graphics2d g2 = Bi. creategraphics (); g2.drawimage (IMG, null, null); fileoutputstream out = NULL; try {out = new fileoutputstream (s);} catch (Java. io. filenotfoundexception Io) {system. out. println ("file not found");} specify imageencoder encoder = required codec. createjpegencoder (out); incluencodeparam Param = encoder. getdefajpegincluencodeparam (BI); Param. setquality (1f, false); // encoder without compressing the image. setincluencodeparam (PARAM); try {encoder. encode (BI); out. close ();} catch (Java. io. ioexception Io) {system. out. println ("ioexception ");} |
I have applied to create jwebcam as an open-source project and put it in gro. Let's use our imagination to add our own code, such as shooting videos and adding image processing functions.