java

位置:IT落伍者 >> java >> 浏览文章

Java中利用JMF编写摄像头拍照程序


发布日期:2023年08月06日
 
Java中利用JMF编写摄像头拍照程序

我把程序分为两种有趣的和无趣的最近做了几个有趣的项目其中一个应当就算是摄像头拍照程序了用于现场拍照生成照片主要用到Java Media Framework(JMF)

首先到SUN下载最新的JMF然后安装media/jmf/indexjsp

然后说一下需求

. 用摄像头拍照

. 在文本框输入文件名

. 按下拍照按钮获取摄像头内的图像

. 在拍下的照片上有一红框截取固定大小的照片

. 保存为本地图像为jpg格式不得压缩画质

技术关键相信也是大家最感兴趣的部分也就是如何让一个摄像头工作并拍下一张照片了

利用JMF代码很简单

//利用这三个类分别获取摄像头驱动和获取摄像头内的图像流获取到的图像流是一个Swing的Component组件类

public static Player player = null;

private CaptureDeviceInfo di = null;

private MediaLocator ml = null;

//文档中提供的驱动写法为何这么写我也不知

String str = vfw:Logitech USB Video Camera:;

String str = vfw:Microsoft WDM Image Capture (Win):;

di = CaptureDeviceManagergetDevice(str);

ml = digetLocator();

try

{

player = ManagercreateRealizedPlayer(ml);

playerstart();

Component comp;

if ((comp = playergetVisualComponent()) != null)

{

add(comp BorderLayoutNORTH);

}

}

catch (Exception e)

{

eprintStackTrace();

}

接下来就是点击拍照获取摄像头内的当前图像

代码也是很简单

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

if (c == capture)//如果按下的是拍照按钮

{

FrameGrabbingControl fgc =(FrameGrabbingControl) playergetControl(ntrolFrameGrabbingControl);

buf = fgcgrabFrame(); // 获取当前祯并存入Buffer类

btoi = new BufferToImage((VideoFormat) bufgetFormat());

img = btoicreateImage(buf); // show the image

imgpanelsetImage(img);

}

保存图像的就不多说了以下为示例代码

BufferedImage bi = (BufferedImage) createImage(imgWidth imgHeight);

GraphicsD g = bicreateGraphics();

gdrawImage(img null null);

FileOutputStream out = null;

try

{

out = new FileOutputStream(s);

}

catch (javaioFileNotFoundException io)

{

Systemoutprintln(File Not Found);

}

JPEGImageEncoder encoder = JPEGCodeccreateJPEGEncoder(out);

JPEGEncodeParam param = encodergetDefaultJPEGEncodeParam(bi);

paramsetQuality(f false);//不压缩图像

encodersetJPEGEncodeParam(param);

try

{

encoderencode(bi);

outclose();

}

catch (javaioIOException io)

{

Systemoutprintln(IOException);

}

已经申请将JWebCam建立为一个开源项目放到GRO大家发挥自己的想象力加入自己的代码吧比如拍摄视频添加图像处理功能等等

上一篇:Java SE 6中XML数字签名标准Java接口

下一篇:谈谈各种JAVA中的调用程序方式