首先到SUN下載最新的JMF,然后安裝。http://java.sun.com/products/java-media/jmf/index.jsp
然后,說一下需求
1. 用攝像頭拍照
2. 在文本框輸入文件名
3. 按下拍照按鈕,獲取攝像頭內(nèi)的圖像
4. 在拍下的照片上有一紅框截取固定大小的照片。
5. 保存為本地圖像為jpg格式,不得壓縮畫質(zhì)
技術(shù)關(guān)鍵,相信也是大家最感興趣的部分也就是如何讓一個攝像頭工作,并拍下一張照片了。
利用JMF,代碼很簡單:
//利用這三個類分別獲取攝像頭驅(qū)動,和獲取攝像頭內(nèi)的圖像流,獲取到的圖像流是一個Swing的Component組件類
1
public static Player player = null;
2
private CaptureDeviceInfo di = null;
3
private MediaLocator ml = null;
4
String str1 = "vfw:Logitech USB Video Camera:0";
5
String str2 = "vfw:Microsoft WDM Image Capture (Win32):0";
6
di = CaptureDeviceManager.getDevice(str2);
7
ml = di.getLocator();
8
try
9
{
10
player = Manager.createRealizedPlayer(ml);
11
player.start();
12
Component comp;
13
if ((comp = player.getVisualComponent()) != null)
14
{
15
add(comp, BorderLayout.NORTH);
16
}
17
}
18
catch (Exception e)
19
{
20
e.printStackTrace();
21
}

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

接下來就是點擊拍照,獲取攝像頭內(nèi)的當(dāng)前圖像。
代碼也是很簡單:
1
private JButton capture;
2
private Buffer buf = null;
3
private BufferToImage btoi = null;
4
private ImagePanel imgpanel = null;
5
private Image img = null;
6
private ImagePanel imgpanel = null;
7
JComponent c = (JComponent) e.getSource();
8
if (c == capture)//如果按下的是拍照按鈕 http://www.5a520.cn
9
{
10
FrameGrabbingControl fgc =(FrameGrabbingControl)player.getControl
11
("javax.media.control.FrameGrabbingControl");
12
buf = fgc.grabFrame(); // 獲取當(dāng)前禎并存入Buffer類 http://www.bt285.cn
13
btoi = new BufferToImage((VideoFormat) buf.getFormat());
14
img = btoi.createImage(buf); // show the image
15
imgpanel.setImage(img);
16
}

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

保存圖像的就不多說了,以下為示例代碼
1
BufferedImage bi = (BufferedImage) createImage(imgWidth, imgHeight);
2
Graphics2D g2 = bi.createGraphics();
3
g2.drawImage(img, null, null);
4
FileOutputStream out = null;
5
try
6
{
7
out = new FileOutputStream(s);
8
}
9
catch (java.io.FileNotFoundException io)
10
{
11
System.out.println("File Not Found");
12
}
13
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
14
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
15
param.setQuality(1f, false);//不壓縮圖像 http://www.bt285.cn
16
encoder.setJPEGEncodeParam(param);
17
try
18
{
19
encoder.encode(bi);
20
out.close();
21
}
22
catch (java.io.IOException io)
23
{
24
System.out.println("IOException");
25
}

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

From:http://www.aygfsteel.com/fundei/archive/2009/05/21/271147.html