/***************************************** 示範利用呼叫外部ffmpeg取得webcam影像 *************************************************/ import java.awt.*; import javax.swing.*; import java.awt.event.*; public class ui44 extends JFrame implements ActionListener { Container c; JLabel lab; JButton bot; Image img=null; ImageIcon icon=null; java.awt.image.BufferedImage bi=new java.awt.image.BufferedImage(320,240,java.awt.image.BufferedImage.TYPE_INT_RGB); public ui44() //建構元 { super("呼叫外部ffmpeg取得webcam影像"); c=getContentPane(); setSize(640,480); bot=new JButton("取影像"); lab=new JLabel(); c.setLayout(new FlowLayout(FlowLayout.CENTER));//設定為流水版面設定 //注意加入元件的順序 c.add(bot); c.add(lab); bot.addActionListener(this);//設定自己為bot0按鈕的傾聽者 setVisible(true); } public void paint(Graphics g) //真正的畫圖設定 { super.paint(g);//畫出元件 } public void actionPerformed(ActionEvent e) //按鈕事件的處理方法 { java.io.BufferedInputStream inp; java.io.BufferedOutputStream out; java.io.BufferedInputStream err; byte errtmp[]=new byte[2000]; byte tmp[]=new byte[320*240*3]; int RAW[] = new int[320*240]; int index,more,R,G,B,i,cpt; String ins; try { //利用ffmpeg 把影像輸出到標準輸出,由java讀入tmp陣列中 Process prc=Runtime.getRuntime().exec("ffmpeg/bin/ffmpeg.exe -f vfwcap -s 320x240 -r 8 -i 0 -an -pix_fmt rgb24 -f rawvideo - "); inp= new java.io.BufferedInputStream(prc.getInputStream()); out=new java.io.BufferedOutputStream(prc.getOutputStream()); err=new java.io.BufferedInputStream(prc.getErrorStream()); err.read(errtmp, 0, err.available()); index = 0; while (index < tmp.length) { more=inp.read(tmp, index, tmp.length-index); if (more<0) more=0; index = index+more; } err.read(errtmp, 0, err.available()); //一次把所有資料組成圖檔 for (i = 0; i < RAW.length; i++) { cpt = i * 3; R = (int) tmp[cpt++] & 0xff; G = (int) tmp[cpt++] & 0xff; B = (int) tmp[cpt] & 0xff; RAW[i] = (R << 16) | (G << 8) | (B); } bi.setRGB(0, 0, 320, 240, RAW, 0, 320); img=(Image)bi; icon=new ImageIcon(img); lab.setIcon(icon); repaint(); inp.close(); err.close(); } catch (Exception ee) { System.out.println(ee.toString()); } } /***主程式***/ public static void main(String args[]) //程式起點 { ui44 app=new ui44(); //畫圖 app.addWindowListener(new WindowAdapter(){ //匿名內部類別 public void windowClosing(WindowEvent e) { System.exit(0); } }); //處理視窗關閉要求 } }