JMF做USB摄像头刷卡拍照
拍照原理:
第一步:捕获摄像头视频
  captureDeviceInfo=CaptureDeviceManager.getDevice("vfw:Microsoft    
                  WDM Image Capture (Win32):0"); //这里放置的是视频驱动
  mediaLocator = new MediaLocator("vfw://0"); //这里是视频地址  确定所 
                                                         需协议和媒体资源的位置
  mediaLocator =  captureDeviceInfo.getLocator(); 
  DataSource ds = new DataSource();   //数据源
  ds.setLocator(mediaLocator);        //设置定位器      
  try {
        Manager.setHint(Manager.LIGHTWEIGHT_RENDERER,newBoolean(true));    //set Hint设置提示 LIGHTWEIGHT RENDERER轻量级渲染器会使图像显示效果更好
            player=Manager.createRealizedPlayer(mediaLocator);                  //将本地视频绑定到播放对象中,数据源绑定.  
            player.start();                 //启动,一般分为6个状态
    } catch (NoPlayerException e) {
            e.printStackTrace();
    } catch (CannotRealizeException e) {
            e.printStackTrace();
    } catch (IOException e) {
            e.printStackTrace();
    }
第二步:抓取视频帧(拍照)
public void actionPerformed(ActionEvent e) { //拍照事件
  player.start();
  System.out.println("走了");
  //Frame Grabbing Controlattendance 帧抓取控制
  FrameGrabbingControl fgc=(FrameGrabbingControl)player.getControl
  ("javax.media.control.FrameGrabbingControl");//加载帧抓取控制 jar包
  buffer=fgc.grabFrame();                  //grabFrameFrame 抢帧
  bufferToImage=newBufferToImage((VideoFormat)buffer.getFormat());
  //bufferToImage 缓冲区图像  getFormat 获得格式  VideoFormat视频格式
  p_w_picpath=bufferToImage.createImage(buffer);        
  p_w_picpathPanel.setImage(p_w_picpath);
  saveImage(p_w_picpath,"D:/photo/test.jpg");    //设置照片名称和保存图像
  player.close();
}
需要思考的问题:
由于USB摄像头是独享的,所以在整个系统中只能加载一次摄像头驱动。
导致的后果:
1.直接后果就是不能实现拍照预览功能!
2.如果首先开启本系统那么其它视频软件就不能运行了,相反如果首先开启其它视频软件那么本系统也不能运行!
(关于USB摄像头是独享性在我的另一片博文有详细介绍,希望看过文章的博友能够给个评论! http://xieyang.blog.51cto.com/2375086/699193)
案例:
 
    
    
    
    
  1. import java.awt.BorderLayout;   
  2.   import java.awt.Component;   
  3.   import java.awt.Graphics;   
  4.   import java.awt.GraphicsConfiguration;   
  5.   import java.awt.GraphicsDevice;   
  6.   import java.awt.GraphicsEnvironment;   
  7.   import java.awt.HeadlessException;   
  8.   import java.awt.Image;   
  9.   import java.awt.Transparency;   
  10.   import java.awt.event.ActionEvent;   
  11.   import java.awt.event.ActionListener;   
  12.   import java.awt.event.WindowAdapter;   
  13.   import java.awt.event.WindowEvent;   
  14.   import java.awt.p_w_picpath.BufferedImage;   
  15.   import java.awt.p_w_picpath.ColorModel;   
  16.   import java.awt.p_w_picpath.PixelGrabber;   
  17.   import java.io.File;   
  18.   import java.io.IOException;   
  19.   import java.util.Vector;   
  20.      
  21.   import javax.p_w_picpathio.ImageIO;   
  22.   import javax.media.Buffer;   
  23.   import javax.media.CaptureDeviceInfo;   
  24.   import javax.media.CaptureDeviceManager;   
  25.   import javax.media.Format;   
  26.   import javax.media.MediaLocator;   
  27.   import javax.media.NoPlayerException;   
  28.   import javax.media.control.FrameGrabbingControl;   
  29.   import javax.media.format.RGBFormat;   
  30.   import javax.media.format.VideoFormat;   
  31.   import javax.media.protocol.DataSource;   
  32.   import javax.media.protocol.PushBufferDataSource;   
  33.   import javax.media.util.BufferToImage;   
  34.   import javax.swing.ImageIcon;   
  35.   import javax.swing.JButton;   
  36.   import javax.swing.JPanel;   
  37.      
  38.   import jmapps.jmstudio.CaptureDialog;   
  39.   import jmapps.ui.PlayerFrame;   
  40.   import jmapps.util.CDSWrapper;   
  41.   import jmapps.util.JMFUtils;   
  42.      
  43.   public class Demo001 extends PlayerFrame {   
  44.      
  45.       public Demo001() {   
  46.           super(null"视频捕获窗口");   
  47.       }   
  48.      
  49.       DataSource dataSource;          //数据源  
  50.      
  51.       private CaptureDeviceInfo infor;  //获取视频设备 每个设备都对应着一个CaptureDeviceInfo对象 
  52.      
  53.       //媒体定位器 在使用设备截取多媒体数据前,还需要从CaptureDeviceInfo中获取MediaLocator对象,使媒体定位器 
  54.       //MediaLocator指向该设备 
  55.       private MediaLocator mediaLocator;   
  56.      
  57.       String str1 = "vfw:Logitech USB Video Camera:0";   
  58.       String str2 = "vfw:Microsoft WDM Image Capture (Win32):0";  
  59.      
  60.       private String url = "vfw:Microsoft WDM Image Capture (Win32):0"//视频设备驱动  
  61.      
  62.       private Component com;   //定义播放组件变量  组件 
  63.      
  64.       private JPanel panel;   
  65.      
  66.       private int captureCount = 0;   
  67.      
  68.       FrameGrabbingControl controlGrabber;   //FrameGrabbingControl 抓控制框架 
  69.      
  70.       public void play() {   
  71.        //mediaPlayerCurrent当前媒体播放器 State状态  
  72.           if (mediaPlayerCurrent.getState() != mediaPlayerCurrent.Started) {   
  73.               mediaPlayerCurrent.start();   
  74.           }   
  75.       }   
  76.      
  77.       private void init() throws NoPlayerException, IOException {   
  78.           
  79.        // setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);   
  80.           String nameCaptureDeviceAudio = null;  //捕获音频装置 
  81.           String nameCaptureDeviceVideo = null;  //捕获视频装置 
  82.           CaptureDialog dialogCapture = new CaptureDialog(thisnull);   //捕获对话框 既select cuptrue Device 
  83.           dialogCapture.show();  //显示  
  84.           if (dialogCapture.getAction() == CaptureDialog.ACTION_CANCEL)   
  85.               return;   
  86.           CaptureDeviceInfo cdi = dialogCapture.getAudioDevice();  //CaptureDeviceInfo捕获硬件设备信息对象 
  87.           if (cdi != null && dialogCapture.isAudioDeviceUsed())  //AudioDeviceUsed 使用音频设备 
  88.               nameCaptureDeviceAudio = cdi.getName();   
  89.           cdi = dialogCapture.getVideoDevice();   
  90.           if (cdi != null && dialogCapture.isVideoDeviceUsed())  //VideoDeviceUsed 使用视频设备 
  91.               nameCaptureDeviceVideo = cdi.getName();   
  92.            
  93.           dataSource = JMFUtils.createCaptureDataSource(nameCaptureDeviceAudio,   
  94.                   dialogCapture.getAudioFormat(), nameCaptureDeviceVideo,  //AudioFormat 音频格式 
  95.                   dialogCapture.getVideoFormat());                         //VideoFormat 视频格式 
  96.           DataSource cdswrapper = new CDSWrapper(   //包装数据源 
  97.                   (PushBufferDataSource) dataSource);  // PushBufferDataSource 推入缓冲区的数据源 
  98.           dataSource = cdswrapper;   
  99.           dataSource.connect();  //connect 连接 
  100.           open(dataSource);   
  101.           JPanel controlPanel = new JPanel();   
  102.           controlPanel.setName("controlPnael is here");   
  103.           add(BorderLayout.SOUTH, controlPanel);   
  104.           JButton capture = new JButton("拍照");   
  105.            
  106.           //拍照代码 
  107.           capture.addActionListener(new ActionListener() {   
  108.               
  109.            public void actionPerformed(ActionEvent arg0) {   //actionPerformed 执行的操作 
  110.                   mediaPlayerCurrent.stop();   
  111.                   Buffer bufferFrame;   
  112.                   BufferToImage bufferToImage;  //缓存影像 
  113.                   Image p_w_picpath;   
  114.                   BufferedImage bi;   
  115.                   controlGrabber = (FrameGrabbingControl) mediaPlayerCurrent  //媒体播放器电流 
  116.                           .getControl("javax.media.control.FrameGrabbingControl");   //加载帧抓取控制 jar包 
  117.                   bufferFrame = controlGrabber.grabFrame();   //grabFrameFrame 抢帧 
  118.                   bufferToImage = new BufferToImage((VideoFormat) bufferFrame   
  119.                           .getFormat());   //bufferToImage 缓冲区图像  getFormat 获得格式  VideoFormat视频格式 
  120.                   p_w_picpath = bufferToImage.createImage(bufferFrame);   
  121.      
  122.                   File out = new File("capture" + (++captureCount) + ".png");   
  123.                   try {   
  124.                       bi = toBufferedImage(p_w_picpath);   
  125.                       ImageIO.write(bi, "png", out);   //把照片保存到特定目录去 
  126.                   } catch (IOException e1) {   
  127.                       e1.printStackTrace();   
  128.                   }   
  129.      
  130.                   mediaPlayerCurrent.start();   
  131.      
  132.               }   
  133.           });   
  134.      
  135.           controlPanel.add(BorderLayout.CENTER, capture);  //把拍照按钮加载到面板中去 
  136.      
  137.           JButton playStop = new JButton("暂停");   
  138.           // add(BorderLayout.SOUTH,playControl);   
  139.            
  140.           //暂停代码 
  141.           playStop.addActionListener(new ActionListener() {   
  142.      
  143.               // @Override   
  144.               public void actionPerformed(ActionEvent arg0) {   
  145.                   mediaPlayerCurrent.stop();   
  146.      
  147.               }   
  148.           });   
  149.           controlPanel.add(BorderLayout.EAST, playStop);   
  150.      
  151.           JButton playStart = new JButton("开始");   
  152.           // add(BorderLayout.SOUTH,playControl);   
  153.           //开始代码 
  154.           playStart.addActionListener(new ActionListener() {   
  155.      
  156.               // @Override   
  157.               public void actionPerformed(ActionEvent arg0) {   
  158.                   // mediaPlayerCurrent.stop();   
  159.                   if (mediaPlayerCurrent.getState() != mediaPlayerCurrent.Started) {   
  160.                       mediaPlayerCurrent.start();   
  161.                   }   
  162.               }   
  163.           });   
  164.           controlPanel.add(BorderLayout.WEST, playStart);   
  165.           addWindowListener(new WindowAdapter() {  //Window Adapter 窗口适配器 
  166.            
  167.            public void windowDeiconified(WindowEvent e) { 
  168.            mediaPlayerCurrent.stop();   
  169.                   Buffer bufferFrame;   
  170.                   BufferToImage bufferToImage;  //缓存影像 
  171.                   Image p_w_picpath;   
  172.                   BufferedImage bi;   
  173.                   controlGrabber = (FrameGrabbingControl) mediaPlayerCurrent  //媒体播放器电流 
  174.                           .getControl("javax.media.control.FrameGrabbingControl");   //加载帧抓取控制 jar包 
  175.                   bufferFrame = controlGrabber.grabFrame();   //grabFrameFrame 抢帧 
  176.                   bufferToImage = new BufferToImage((VideoFormat) bufferFrame   
  177.                           .getFormat());   //bufferToImage 缓冲区图像  getFormat 获得格式  VideoFormat视频格式 
  178.                   p_w_picpath = bufferToImage.createImage(bufferFrame);   
  179.      
  180.                   File out = new File("capture" + (++captureCount) + ".png");   
  181.                   try {   
  182.                       bi = toBufferedImage(p_w_picpath);   
  183.                       ImageIO.write(bi, "png", out);   //把照片保存到特定目录去 
  184.                   } catch (IOException e1) {   
  185.                       e1.printStackTrace();   
  186.                   }   
  187.      
  188.                   mediaPlayerCurrent.start();   
  189.      } 
  190.  @Override   
  191.               public void windowClosing(WindowEvent e) { //关闭窗口事件   
  192.                   mediaPlayerCurrent.close();   //播放关闭 
  193.                   dataSource.disconnect();   //断开数据源 
  194.                   System.out.println("exit.....");   
  195.                   System.exit(0);   //关闭窗口 
  196.      
  197.               }   
  198.           });   
  199.       }   
  200.      
  201.       //拍照 
  202.       public void Photo(){ 
  203.        mediaPlayerCurrent.stop();   
  204.           Buffer bufferFrame;   
  205.           BufferToImage bufferToImage;  //缓存影像 
  206.           Image p_w_picpath;   
  207.           BufferedImage bi;   
  208.           controlGrabber = (FrameGrabbingControl) mediaPlayerCurrent  //媒体播放器电流 
  209.                   .getControl("javax.media.control.FrameGrabbingControl");   //加载帧抓取控制 jar包 
  210.           bufferFrame = controlGrabber.grabFrame();   //grabFrameFrame 抢帧 
  211.           bufferToImage = new BufferToImage((VideoFormat) bufferFrame   
  212.                   .getFormat());   //bufferToImage 缓冲区图像  getFormat 获得格式  VideoFormat视频格式 
  213.           p_w_picpath = bufferToImage.createImage(bufferFrame);   
  214.           File out = new File("capture" + (++captureCount) + ".png");   
  215.           try {   
  216.               bi = toBufferedImage(p_w_picpath);   
  217.               ImageIO.write(bi, "png", out);   //把照片保存到特定目录去 
  218.           } catch (IOException e1) {   
  219.               e1.printStackTrace();   
  220.           }   
  221.           mediaPlayerCurrent.start();   
  222.       } 
  223.        
  224.       public static boolean hasAlpha(Image p_w_picpath) {   
  225.           // If buffered p_w_picpath, the color model is readily available   
  226.           if (p_w_picpath instanceof BufferedImage) {   
  227.               BufferedImage bp_w_picpath = (BufferedImage) p_w_picpath;   
  228.               return bp_w_picpath.getColorModel().hasAlpha();   //ColorModel颜色模型 
  229.           }   
  230.           // Use a pixel grabber to retrieve the p_w_picpath's color model;   
  231.           // grabbing a single pixel is usually sufficient   
  232.           PixelGrabber pg = new PixelGrabber(p_w_picpath, 0011false);  //像素采集卡 
  233.           try {   
  234.               pg.grabPixels();   //抢像素 
  235.           } catch (InterruptedException e) {   
  236.           }   
  237.      
  238.           // Get the p_w_picpath's color model   
  239.           ColorModel cm = pg.getColorModel();   //颜色模型 
  240.           return cm.hasAlpha();   
  241.       }   
  242.      
  243.       public static BufferedImage toBufferedImage(Image p_w_picpath) {   
  244.           if (p_w_picpath instanceof BufferedImage) {   
  245.               return (BufferedImage) p_w_picpath;   
  246.           }   
  247.      
  248.           // This code ensures that all the pixels in the p_w_picpath are loaded   
  249.           p_w_picpath = new ImageIcon(p_w_picpath).getImage();   
  250.      
  251.           // Determine if the p_w_picpath has transparent pixels; for this method's   
  252.           // implementation, see e661 Determining If an Image Has Transparent   
  253.           // Pixels   
  254.           boolean hasAlpha = hasAlpha(p_w_picpath);   
  255.      
  256.           // Create a buffered p_w_picpath with a format that's compatible with the   
  257.           // screen   
  258.           BufferedImage bp_w_picpath = null;   
  259.           GraphicsEnvironment ge = GraphicsEnvironment   //图像环境 
  260.                   .getLocalGraphicsEnvironment();  //获得本地图像环境 
  261.           try {   
  262.               // Determine the type of transparency of the new buffered p_w_picpath   
  263.               int transparency = Transparency.OPAQUE;   //transparency 透明度 
  264.               if (hasAlpha) {   
  265.                   transparency = Transparency.BITMASK;   
  266.               }   
  267.      
  268.               // Create the buffered p_w_picpath   
  269.               GraphicsDevice gs = ge.getDefaultScreenDevice();  //默认皮肤设备 
  270.               GraphicsConfiguration gc = gs.getDefaultConfiguration();   //图形配置 
  271.               bp_w_picpath = gc.createCompatibleImage(p_w_picpath.getWidth(null), p_w_picpath   
  272.                       .getHeight(null), transparency);   
  273.           } catch (HeadlessException e) {   
  274.               // The system does not have a screen   
  275.               System.err.println("The system does not have a screen!");   
  276.               System.exit(-1);   
  277.           }   
  278.      
  279.           if (bp_w_picpath == null) {   
  280.               // Create a buffered p_w_picpath using the default color model   
  281.               int type = BufferedImage.TYPE_INT_RGB;   
  282.               if (hasAlpha) {   
  283.                   type = BufferedImage.TYPE_INT_ARGB;   
  284.               }   
  285.               bp_w_picpath = new BufferedImage(p_w_picpath.getWidth(null), p_w_picpath   
  286.                       .getHeight(null), type);   
  287.           }   
  288.      
  289.           // Copy p_w_picpath to buffered p_w_picpath   
  290.           Graphics g = bp_w_picpath.createGraphics();   
  291.      
  292.           // Paint the p_w_picpath onto the buffered p_w_picpath   
  293.           g.drawImage(p_w_picpath, 00null);   
  294.           g.dispose();   
  295.      
  296.           return bp_w_picpath;   
  297.       }   
  298.      
  299.       private MediaLocator autoDetect() {// 自动识别功能函数   
  300.           MediaLocator ml = null// 视频采集设备对应的MediaLocator   
  301.           VideoFormat currentFormat = null;// 用户定制获得视频采集设备支持的格式   
  302.           Format setFormat = null;// 用户定制视频采集设备输出的格式   
  303.           Format[] videoFormats = null;// 视频采集设备支持的所有格式   
  304.           System.out.println(" AutoDetect for VFW");// VFW:微软的 Video for Windows   
  305.           // 获得当前所有设备列表  调用getDeviceList()方法获取设备的列表 
  306.           //通过CaptureDeviceManager对象获取系统中可用的视频和音频设备,并通过调用getDeviceList方法获得设备的列表 
  307.           Vector deviceList = CaptureDeviceManager.getDeviceList(null);   
  308.           CaptureDeviceInfo device = CaptureDeviceManager.getDevice(url);   
  309.           if (deviceList != null) {   
  310.               // 根据设备列表,找出可用设备名称   
  311.               for (int i = 0; i < deviceList.size(); i++) {   
  312.                   try {   
  313.                       CaptureDeviceInfo di = (CaptureDeviceInfo) deviceList   
  314.                               .elementAt(i);   
  315.                       // 如果设备名称以vfw开头   
  316.                       if (di.getName().startsWith("vfw:")) {   
  317.                           // 获得所有支持RGB格式   
  318.                           videoFormats = di.getFormats();   
  319.                           for (int j = 0; j < videoFormats.length; j++) {   
  320.                               // 我们只需要第一种RGB格式   
  321.                               if (videoFormats[j] instanceof RGBFormat) {   
  322.                                   currentFormat = (RGBFormat) videoFormats[i];   
  323.                                   break;   
  324.                               }   
  325.                           }   
  326.                           if (currentFormat == null) {   
  327.                               System.err.println("Search For RGBFormat Failed");   
  328.                               System.exit(-1);   
  329.                           }   
  330.                           // 通过设备,获得MediaLocator,这个很重要   
  331.                           ml = di.getLocator();   
  332.                       }   
  333.                   } catch (Exception npe) {   
  334.                       System.err.println("Unable to get Processor for device");   
  335.                       System.exit(-1);   
  336.                   }   
  337.               }   
  338.           } else {   
  339.               System.err.println("No Capture Device OK");   
  340.               System.exit(-1);   
  341.           }   
  342.           mediaLocator = ml;   
  343.           return ml;// 返回可用的设备medialocator   
  344.       }   
  345.      
  346.       public static void main(String[] args) throws NoPlayerException,   
  347.               IOException {   
  348.           Demo001 demo = new Demo001();   
  349.           demo.setSize(100100);   
  350.           demo.autoDetect();   
  351.           demo.init();   
  352.           demo.play();   
  353.           demo.setVisible(true);   
  354.       }   
  355.   }