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)
案例:
- import java.awt.BorderLayout;
- import java.awt.Component;
- import java.awt.Graphics;
- import java.awt.GraphicsConfiguration;
- import java.awt.GraphicsDevice;
- import java.awt.GraphicsEnvironment;
- import java.awt.HeadlessException;
- import java.awt.Image;
- import java.awt.Transparency;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import java.awt.event.WindowAdapter;
- import java.awt.event.WindowEvent;
- import java.awt.p_w_picpath.BufferedImage;
- import java.awt.p_w_picpath.ColorModel;
- import java.awt.p_w_picpath.PixelGrabber;
- import java.io.File;
- import java.io.IOException;
- import java.util.Vector;
- import javax.p_w_picpathio.ImageIO;
- import javax.media.Buffer;
- import javax.media.CaptureDeviceInfo;
- import javax.media.CaptureDeviceManager;
- import javax.media.Format;
- import javax.media.MediaLocator;
- import javax.media.NoPlayerException;
- import javax.media.control.FrameGrabbingControl;
- import javax.media.format.RGBFormat;
- import javax.media.format.VideoFormat;
- import javax.media.protocol.DataSource;
- import javax.media.protocol.PushBufferDataSource;
- import javax.media.util.BufferToImage;
- import javax.swing.ImageIcon;
- import javax.swing.JButton;
- import javax.swing.JPanel;
- import jmapps.jmstudio.CaptureDialog;
- import jmapps.ui.PlayerFrame;
- import jmapps.util.CDSWrapper;
- import jmapps.util.JMFUtils;
- public class Demo001 extends PlayerFrame {
- public Demo001() {
- super(null, "视频捕获窗口");
- }
- DataSource dataSource; //数据源
- private CaptureDeviceInfo infor; //获取视频设备 每个设备都对应着一个CaptureDeviceInfo对象
- //媒体定位器 在使用设备截取多媒体数据前,还需要从CaptureDeviceInfo中获取MediaLocator对象,使媒体定位器
- //MediaLocator指向该设备
- private MediaLocator mediaLocator;
- String str1 = "vfw:Logitech USB Video Camera:0";
- String str2 = "vfw:Microsoft WDM Image Capture (Win32):0";
- private String url = "vfw:Microsoft WDM Image Capture (Win32):0"; //视频设备驱动
- private Component com; //定义播放组件变量 组件
- private JPanel panel;
- private int captureCount = 0;
- FrameGrabbingControl controlGrabber; //FrameGrabbingControl 抓控制框架
- public void play() {
- //mediaPlayerCurrent当前媒体播放器 State状态
- if (mediaPlayerCurrent.getState() != mediaPlayerCurrent.Started) {
- mediaPlayerCurrent.start();
- }
- }
- private void init() throws NoPlayerException, IOException {
- // setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
- String nameCaptureDeviceAudio = null; //捕获音频装置
- String nameCaptureDeviceVideo = null; //捕获视频装置
- CaptureDialog dialogCapture = new CaptureDialog(this, null); //捕获对话框 既select cuptrue Device
- dialogCapture.show(); //显示
- if (dialogCapture.getAction() == CaptureDialog.ACTION_CANCEL)
- return;
- CaptureDeviceInfo cdi = dialogCapture.getAudioDevice(); //CaptureDeviceInfo捕获硬件设备信息对象
- if (cdi != null && dialogCapture.isAudioDeviceUsed()) //AudioDeviceUsed 使用音频设备
- nameCaptureDeviceAudio = cdi.getName();
- cdi = dialogCapture.getVideoDevice();
- if (cdi != null && dialogCapture.isVideoDeviceUsed()) //VideoDeviceUsed 使用视频设备
- nameCaptureDeviceVideo = cdi.getName();
- dataSource = JMFUtils.createCaptureDataSource(nameCaptureDeviceAudio,
- dialogCapture.getAudioFormat(), nameCaptureDeviceVideo, //AudioFormat 音频格式
- dialogCapture.getVideoFormat()); //VideoFormat 视频格式
- DataSource cdswrapper = new CDSWrapper( //包装数据源
- (PushBufferDataSource) dataSource); // PushBufferDataSource 推入缓冲区的数据源
- dataSource = cdswrapper;
- dataSource.connect(); //connect 连接
- open(dataSource);
- JPanel controlPanel = new JPanel();
- controlPanel.setName("controlPnael is here");
- add(BorderLayout.SOUTH, controlPanel);
- JButton capture = new JButton("拍照");
- //拍照代码
- capture.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent arg0) { //actionPerformed 执行的操作
- mediaPlayerCurrent.stop();
- Buffer bufferFrame;
- BufferToImage bufferToImage; //缓存影像
- Image p_w_picpath;
- BufferedImage bi;
- controlGrabber = (FrameGrabbingControl) mediaPlayerCurrent //媒体播放器电流
- .getControl("javax.media.control.FrameGrabbingControl"); //加载帧抓取控制 jar包
- bufferFrame = controlGrabber.grabFrame(); //grabFrameFrame 抢帧
- bufferToImage = new BufferToImage((VideoFormat) bufferFrame
- .getFormat()); //bufferToImage 缓冲区图像 getFormat 获得格式 VideoFormat视频格式
- p_w_picpath = bufferToImage.createImage(bufferFrame);
- File out = new File("capture" + (++captureCount) + ".png");
- try {
- bi = toBufferedImage(p_w_picpath);
- ImageIO.write(bi, "png", out); //把照片保存到特定目录去
- } catch (IOException e1) {
- e1.printStackTrace();
- }
- mediaPlayerCurrent.start();
- }
- });
- controlPanel.add(BorderLayout.CENTER, capture); //把拍照按钮加载到面板中去
- JButton playStop = new JButton("暂停");
- // add(BorderLayout.SOUTH,playControl);
- //暂停代码
- playStop.addActionListener(new ActionListener() {
- // @Override
- public void actionPerformed(ActionEvent arg0) {
- mediaPlayerCurrent.stop();
- }
- });
- controlPanel.add(BorderLayout.EAST, playStop);
- JButton playStart = new JButton("开始");
- // add(BorderLayout.SOUTH,playControl);
- //开始代码
- playStart.addActionListener(new ActionListener() {
- // @Override
- public void actionPerformed(ActionEvent arg0) {
- // mediaPlayerCurrent.stop();
- if (mediaPlayerCurrent.getState() != mediaPlayerCurrent.Started) {
- mediaPlayerCurrent.start();
- }
- }
- });
- controlPanel.add(BorderLayout.WEST, playStart);
- addWindowListener(new WindowAdapter() { //Window Adapter 窗口适配器
- public void windowDeiconified(WindowEvent e) {
- mediaPlayerCurrent.stop();
- Buffer bufferFrame;
- BufferToImage bufferToImage; //缓存影像
- Image p_w_picpath;
- BufferedImage bi;
- controlGrabber = (FrameGrabbingControl) mediaPlayerCurrent //媒体播放器电流
- .getControl("javax.media.control.FrameGrabbingControl"); //加载帧抓取控制 jar包
- bufferFrame = controlGrabber.grabFrame(); //grabFrameFrame 抢帧
- bufferToImage = new BufferToImage((VideoFormat) bufferFrame
- .getFormat()); //bufferToImage 缓冲区图像 getFormat 获得格式 VideoFormat视频格式
- p_w_picpath = bufferToImage.createImage(bufferFrame);
- File out = new File("capture" + (++captureCount) + ".png");
- try {
- bi = toBufferedImage(p_w_picpath);
- ImageIO.write(bi, "png", out); //把照片保存到特定目录去
- } catch (IOException e1) {
- e1.printStackTrace();
- }
- mediaPlayerCurrent.start();
- }
- @Override
- public void windowClosing(WindowEvent e) { //关闭窗口事件
- mediaPlayerCurrent.close(); //播放关闭
- dataSource.disconnect(); //断开数据源
- System.out.println("exit.....");
- System.exit(0); //关闭窗口
- }
- });
- }
- //拍照
- public void Photo(){
- mediaPlayerCurrent.stop();
- Buffer bufferFrame;
- BufferToImage bufferToImage; //缓存影像
- Image p_w_picpath;
- BufferedImage bi;
- controlGrabber = (FrameGrabbingControl) mediaPlayerCurrent //媒体播放器电流
- .getControl("javax.media.control.FrameGrabbingControl"); //加载帧抓取控制 jar包
- bufferFrame = controlGrabber.grabFrame(); //grabFrameFrame 抢帧
- bufferToImage = new BufferToImage((VideoFormat) bufferFrame
- .getFormat()); //bufferToImage 缓冲区图像 getFormat 获得格式 VideoFormat视频格式
- p_w_picpath = bufferToImage.createImage(bufferFrame);
- File out = new File("capture" + (++captureCount) + ".png");
- try {
- bi = toBufferedImage(p_w_picpath);
- ImageIO.write(bi, "png", out); //把照片保存到特定目录去
- } catch (IOException e1) {
- e1.printStackTrace();
- }
- mediaPlayerCurrent.start();
- }
- public static boolean hasAlpha(Image p_w_picpath) {
- // If buffered p_w_picpath, the color model is readily available
- if (p_w_picpath instanceof BufferedImage) {
- BufferedImage bp_w_picpath = (BufferedImage) p_w_picpath;
- return bp_w_picpath.getColorModel().hasAlpha(); //ColorModel颜色模型
- }
- // Use a pixel grabber to retrieve the p_w_picpath's color model;
- // grabbing a single pixel is usually sufficient
- PixelGrabber pg = new PixelGrabber(p_w_picpath, 0, 0, 1, 1, false); //像素采集卡
- try {
- pg.grabPixels(); //抢像素
- } catch (InterruptedException e) {
- }
- // Get the p_w_picpath's color model
- ColorModel cm = pg.getColorModel(); //颜色模型
- return cm.hasAlpha();
- }
- public static BufferedImage toBufferedImage(Image p_w_picpath) {
- if (p_w_picpath instanceof BufferedImage) {
- return (BufferedImage) p_w_picpath;
- }
- // This code ensures that all the pixels in the p_w_picpath are loaded
- p_w_picpath = new ImageIcon(p_w_picpath).getImage();
- // Determine if the p_w_picpath has transparent pixels; for this method's
- // implementation, see e661 Determining If an Image Has Transparent
- // Pixels
- boolean hasAlpha = hasAlpha(p_w_picpath);
- // Create a buffered p_w_picpath with a format that's compatible with the
- // screen
- BufferedImage bp_w_picpath = null;
- GraphicsEnvironment ge = GraphicsEnvironment //图像环境
- .getLocalGraphicsEnvironment(); //获得本地图像环境
- try {
- // Determine the type of transparency of the new buffered p_w_picpath
- int transparency = Transparency.OPAQUE; //transparency 透明度
- if (hasAlpha) {
- transparency = Transparency.BITMASK;
- }
- // Create the buffered p_w_picpath
- GraphicsDevice gs = ge.getDefaultScreenDevice(); //默认皮肤设备
- GraphicsConfiguration gc = gs.getDefaultConfiguration(); //图形配置
- bp_w_picpath = gc.createCompatibleImage(p_w_picpath.getWidth(null), p_w_picpath
- .getHeight(null), transparency);
- } catch (HeadlessException e) {
- // The system does not have a screen
- System.err.println("The system does not have a screen!");
- System.exit(-1);
- }
- if (bp_w_picpath == null) {
- // Create a buffered p_w_picpath using the default color model
- int type = BufferedImage.TYPE_INT_RGB;
- if (hasAlpha) {
- type = BufferedImage.TYPE_INT_ARGB;
- }
- bp_w_picpath = new BufferedImage(p_w_picpath.getWidth(null), p_w_picpath
- .getHeight(null), type);
- }
- // Copy p_w_picpath to buffered p_w_picpath
- Graphics g = bp_w_picpath.createGraphics();
- // Paint the p_w_picpath onto the buffered p_w_picpath
- g.drawImage(p_w_picpath, 0, 0, null);
- g.dispose();
- return bp_w_picpath;
- }
- private MediaLocator autoDetect() {// 自动识别功能函数
- MediaLocator ml = null; // 视频采集设备对应的MediaLocator
- VideoFormat currentFormat = null;// 用户定制获得视频采集设备支持的格式
- Format setFormat = null;// 用户定制视频采集设备输出的格式
- Format[] videoFormats = null;// 视频采集设备支持的所有格式
- System.out.println(" AutoDetect for VFW");// VFW:微软的 Video for Windows
- // 获得当前所有设备列表 调用getDeviceList()方法获取设备的列表
- //通过CaptureDeviceManager对象获取系统中可用的视频和音频设备,并通过调用getDeviceList方法获得设备的列表
- Vector deviceList = CaptureDeviceManager.getDeviceList(null);
- CaptureDeviceInfo device = CaptureDeviceManager.getDevice(url);
- if (deviceList != null) {
- // 根据设备列表,找出可用设备名称
- for (int i = 0; i < deviceList.size(); i++) {
- try {
- CaptureDeviceInfo di = (CaptureDeviceInfo) deviceList
- .elementAt(i);
- // 如果设备名称以vfw开头
- if (di.getName().startsWith("vfw:")) {
- // 获得所有支持RGB格式
- videoFormats = di.getFormats();
- for (int j = 0; j < videoFormats.length; j++) {
- // 我们只需要第一种RGB格式
- if (videoFormats[j] instanceof RGBFormat) {
- currentFormat = (RGBFormat) videoFormats[i];
- break;
- }
- }
- if (currentFormat == null) {
- System.err.println("Search For RGBFormat Failed");
- System.exit(-1);
- }
- // 通过设备,获得MediaLocator,这个很重要
- ml = di.getLocator();
- }
- } catch (Exception npe) {
- System.err.println("Unable to get Processor for device");
- System.exit(-1);
- }
- }
- } else {
- System.err.println("No Capture Device OK");
- System.exit(-1);
- }
- mediaLocator = ml;
- return ml;// 返回可用的设备medialocator
- }
- public static void main(String[] args) throws NoPlayerException,
- IOException {
- Demo001 demo = new Demo001();
- demo.setSize(100, 100);
- demo.autoDetect();
- demo.init();
- demo.play();
- demo.setVisible(true);
- }
- }