① java代碼如何調用客戶端攝像頭
首先到sun下載最新的jmf,然後安裝。
然後,說一下需求
1. 用攝像頭拍照
2. 在文本框輸入文件名
3. 按下拍照按鈕,獲取攝像頭內的圖像
4. 在拍下的照片上有一紅框截取固定大小的照片。
5. 保存為本地圖像為jpg格式,不得壓縮畫質
技術關鍵,相信也是大家最感興趣的部分也就是如何讓一個攝像頭工作,並拍下一張照片了。
利用jmf,代碼很簡單:
//利用這三個類分別獲取攝像頭驅動,和獲取攝像頭內的圖像流,獲取到的圖像流是一個swing的component組件類
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();
}
接下來就是點擊拍照,獲取攝像頭內的當前圖像。
代碼也是很簡單:
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)//如果按下的是拍照按鈕
{
framegrabbingcontrol fgc =(framegrabbingcontrol) player.getcontrol( "javax.media.control.framegrabbingcontrol ");
buf = fgc.grabframe(); // 獲取當前禎並存入buffer類
btoi = new buffertoimage((videoformat) buf.getformat());
img = btoi.createimage(buf); // show the image
imgpanel.setimage(img);
}
保存圖像的就不多說了,以下為示例代碼
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 ");
}
jpegimageencoder encoder = jpegcodec.createjpegencoder(out);
jpegencodeparam param = encoder.getdefaultjpegencodeparam(bi);
param.setquality(1f, false);//不壓縮圖像
encoder.setjpegencodeparam(param);
try
{
encoder.encode(bi);
out.close();
}
catch (java.io.ioexception io)
{
system.out.println( "ioexception ");
}
把.jar文件導入。下載了jmf後需要安裝,安裝後你的那個jmf目錄下就會有一個lib文件夾裡面有.jar文件,然後打開eclipse,右鍵選擇你的工程-〉屬性-〉java build path-> library-〉add external jars 找到你的jmf目錄下lib的那個文件夾然後選中那些文件導入就ok了。
然後利用工具提供的導入文件幫助,一個一個導就OK了