本程序通过JFrame实时显示本机摄像头图像,并将图像存储到一个缓冲区,当用户用鼠标点击JFrame中任何区域时,显示抓取图像的简单动画,同时保存缓冲区的图像到磁盘文件中。点击JFrame关闭按钮可以退出程序。
实现:
- import java.awt.Graphics2D;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import java.awt.event.MouseAdapter;
- import java.awt.event.MouseEvent;
- import java.awt.image.BufferedImage;
- import java.io.File;
- import java.io.IOException;
-
- import javax.imageio.ImageIO;
- import javax.swing.Timer;
-
- import com.googlecode.javacv.CanvasFrame;
- import com.googlecode.javacv.OpenCVFrameGrabber;
- import com.googlecode.javacv.cpp.opencv_core.IplImage;
- import static com.googlecode.javacv.cpp.opencv_core.cvReleaseImage;
-
- public class CameraCapture {
- public static String savedImageFile = "c:\\tmp\\my.jpg";
-
-
- static class TimerAction implements ActionListener {
- private Graphics2D g;
- private CanvasFrame canvasFrame;
- private int width,height;
-
- private int delta=10;
- private int count = 0;
-
- private Timer timer;
- public void setTimer(Timer timer){
- this.timer = timer;
- }
-
- public TimerAction(CanvasFrame canvasFrame){
- this.g = (Graphics2D)canvasFrame.getCanvas().getGraphics();
- this.canvasFrame = canvasFrame;
- this.width = canvasFrame.getCanvas().getWidth();
- this.height = canvasFrame.getCanvas().getHeight();
- }
- public void actionPerformed(ActionEvent e) {
- int offset = delta*count;
- if(width-offset>=offset && height-offset >= offset) {
- g.drawRect(offset, offset, width-2*offset, height-2*offset);
- canvasFrame.repaint();
- count++;
- }else{
-
- timer.stop();
- count = 0;
- }
- }
- }
-
- public static void main(String[] args) throws Exception {
-
- OpenCVFrameGrabber grabber = new OpenCVFrameGrabber(0);
- grabber.start();
-
-
- CanvasFrame canvasFrame = new CanvasFrame("Camera");
- IplImage image = grabber.grab();
- int width = image.width();
- int height = image.height();
- canvasFrame.setCanvasSize(width, height);
-
-
- final BufferedImage bImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
- Graphics2D bGraphics = bImage.createGraphics();
-
-
- TimerAction timerAction = new TimerAction(canvasFrame);
- final Timer timer=new Timer(10, timerAction);
- timerAction.setTimer(timer);
-
-
- canvasFrame.getCanvas().addMouseListener(new MouseAdapter(){
- public void mouseClicked(MouseEvent e){
- timer.start();
- try {
- ImageIO.write(bImage, "jpg", new File(savedImageFile));
- } catch (IOException e1) {
- e1.printStackTrace();
- }
- }
- });
-
-
- while(canvasFrame.isVisible() && (image=grabber.grab()) != null){
- if(!timer.isRunning()) {
- canvasFrame.showImage(image);
-
- bGraphics.drawImage(image.getBufferedImage(),null,0,0);
- }
- }
-
-
- cvReleaseImage(image);
- grabber.stop();
- canvasFrame.dispose();
- }
-
- }