利用 Java Media Framework (JMF) 開發攝影機拍照應用,可滿足現場拍照、生成照片等需求。本文詳細說明從環境建置、攝影機畫面擷取、固定區域裁切、到高畫質 JPEG 儲存的完整流程。
JMF 透過 CaptureDeviceManager 取得裝置資訊,建立 Player 播放器,並從中取得視覺元件 (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 = player.getVisualComponent();
if (comp != null) {
add(comp, BorderLayout.NORTH);
}
} catch (Exception e) {
e.printStackTrace();
}
透過 FrameGrabbingControl 取得當前幀緩衝區 (Buffer),轉換為 Image 物件。
private JButton capture;
private Buffer buf = null;
private BufferToImage btoi = null;
private ImagePanel imgpanel = null;
private Image img = null;
// 事件處理中
JComponent c = (JComponent) e.getSource();
if (c == capture) {
FrameGrabbingControl fgc = (FrameGrabbingControl) player.getControl("javax.media.control.FrameGrabbingControl");
buf = fgc.grabFrame();
btoi = new BufferToImage((VideoFormat) buf.getFormat());
img = btoi.createImage(buf);
imgpanel.setImage(img); // 顯示於自訂面板
}
建立 BufferedImage 繪製裁切區域,使用 JPEGImageEncoder 設定品質參數 1.0f (無壓縮) 輸出。
BufferedImage bi = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = bi.createGraphics();
g2.drawImage(img, 0, 0, imgWidth, imgHeight, cropX, cropY, cropX + imgWidth, cropY + imgHeight, null);
g2.dispose();
FileOutputStream out = new FileOutputStream(filename);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
param.setQuality(1f, false); // 不壓縮
encoder.setJPEGEncodeParam(param);
encoder.encode(bi);
out.close();
已將專案 JWebCam 申請為開源專案,歡迎開發者加入影片錄製、影像處理、濾鏡特效等功能,發揮創意。