Java gets real-time camera to take pictures (source code attached)

1. Introduction

1 Introduction

Java is a general-purpose programming language that can be used to develop various types of applications, including those involving image processing and camera operation.

        To get a real-time camera to take pictures in Java, you usually use some third-party libraries or APIs , such as OpenCV (Open Source Computer Vision Library) or Java Media Framework (JMF) . These libraries and APIs provide access to camera and image processing functions.

        By using these libraries and APIs, you can write Java code to call the camera and get the video stream in real time . You can then choose to capture an image from the video stream and save it as a picture file . In this way, you can realize the function of obtaining real-time camera to take pictures in Java.

The specific implementation steps may vary depending on the library or API used. You can refer to the sample code below to learn how to implement this function in Java.

2. Purpose

        The purpose of obtaining a real-time camera for taking pictures can be diverse, depending on the specific application scenarios and needs.

        The purpose of obtaining real-time cameras for taking pictures is to use real-time image data to meet the needs of various applications, including image processing, remote communication, monitoring and security, virtual augmented reality, and daily shooting .

  1. Image processing and computer vision : Real-time camera photography can provide real-time image data, which is very important for image processing and computer vision tasks. For example, images captured by cameras can be used for tasks such as face recognition, object detection, and gesture recognition.
  2. Video conferencing and remote communication : Live photography can be used for video conferencing and remote communication, allowing participants to interact and view each other's images in real time. This is especially important in an environment of remote work and remote collaboration.
  3. Real-time monitoring and security system : Real-time monitoring and security system can be realized by obtaining real-time cameras to take pictures. This is very useful for homes, offices, public places and other places that require real-time monitoring and security.
  4. Virtual reality and augmented reality : In virtual reality and augmented reality applications, real-time camera photography can provide images of the real world for interaction with the virtual world. For example, a camera can be used to capture the user's movements and render them in a virtual environment in real time.
  5. Video recording and photo taking functions : Of course, the most basic purpose of obtaining a real-time camera for taking photos is to record and capture images at a specific moment. This can be applied to various application scenarios, such as personal photography, online education, e-commerce, etc.

2. Process

In fact, people are sometimes a little confused when it comes to theory, so we skip those parts and go directly to the code. I've summarized the easier steps, divided into two steps:

  1. import
  2. Function writing

[Note] Before this, we need to have the foundation of Maven . If there is no package import, this step will be a bit troublesome. We need to find the address of the package ourselves, download it locally and import the package.

1. Guide package

Introducing callable packages, this is an important part. Use a third-party library to obtain a video stream.

<!--    github调用摄像头-->
<!-- https://mvnrepository.com/artifact/com.github.sarxos/webcam-capture -->
<dependency>
    <groupId>com.github.sarxos</groupId>
    <artifactId>webcam-capture</artifactId>
    <version>0.3.12</version>
</dependency>

2. Function writing

There are some that use windows to more intuitively display the implementation of functions, and also explain the core code. You can update the code according to your own needs.

2.1, Use swing

Use the swing window to display the acquired video stream screen, and use the swing button click event to capture a screen and save it to a local path.

package com;

import com.github.sarxos.webcam.Webcam;
import com.github.sarxos.webcam.WebcamPanel;
import com.github.sarxos.webcam.WebcamResolution;
import com.github.sarxos.webcam.WebcamUtils;
import com.github.sarxos.webcam.util.ImageUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * 相机
 */
public class SwingWebCam {

    private static JFrame window;

    public static void main(String[] args) throws Exception {
        // 获取默认的摄像头实例
        final Webcam webcam = Webcam.getDefault();
        // 设置摄像头捕获的图像尺寸为VGA
        webcam.setViewSize(WebcamResolution.VGA.getSize());
        // 创建一个WebcamPanel对象,并将摄像头实例传递给它
        WebcamPanel panel = new WebcamPanel(webcam);
        // 设置在图像面板上显示FPS、调试信息和图像尺寸,并进行镜像显示
        panel.setFPSDisplayed(true);
        panel.setDisplayDebugInfo(true);
        panel.setImageSizeDisplayed(true);
        panel.setMirrored(true);
        // 创建一个JFrame窗口对象,并将摄像头面板添加到窗口中
        window = new JFrame("摄像头");
        window.add(panel);
        // 设置窗口的一些属性和可见性
        window.setResizable(true);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.pack();
        window.setVisible(true);

        // 创建一个拍照按钮,并将其添加到窗口底部
        final JButton button = new JButton("拍照");
        window.add(panel, BorderLayout.CENTER);
        window.add(button, BorderLayout.SOUTH);

        window.setResizable(true);
        window.pack();
        window.setVisible(true);
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // 为按钮添加点击事件监听器,实现拍照功能
                button.setEnabled(false);  // 设置按钮不可点击

                // 实现拍照保存-------start
                String fileName = "D://" + System.currentTimeMillis();       // 保存路径即图片名称(不用加后缀)

                // 使用WebcamUtils.capture()方法拍照并保存
                WebcamUtils.capture(webcam, fileName, ImageUtils.FORMAT_PNG);

                // 通过SwingUtilities.invokeLater()方法,在拍照完成后弹出对话框显示拍照成功,并重新启用按钮的点击功能。
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        JOptionPane.showMessageDialog(null, "拍照成功");
                        button.setEnabled(true);    // 设置按钮可点击
                        return;
                    }
                });
                // 实现拍照保存-------end
            }
        });
    }
}

2.2. Core code

The core code only needs to directly call the camera and obtain the video stream to capture and save it in the local path.

//        获取默认的摄像头实例
        final Webcam webcam = Webcam.getDefault();
//        设置摄像头捕获的图像尺寸为VGA
        webcam.setViewSize(WebcamResolution.VGA.getSize());
//        创建一个WebcamPanel对象,并将摄像头实例传递给它
        WebcamPanel panel = new WebcamPanel(webcam);
//        设置在图像面板上显示FPS、调试信息和图像尺寸,并进行镜像显示
        panel.setFPSDisplayed(true);
        panel.setDisplayDebugInfo(true);
        panel.setImageSizeDisplayed(true);
        panel.setMirrored(true);
        //实现拍照保存-------start
        String fileName = "D://" + System.currentTimeMillis();       //保存路径即图片名称(不用加后缀)
        System.out.println(fileName);
//                webcam实例名;fileName:地址;
        WebcamUtils.capture(webcam, fileName, ImageUtils.FORMAT_PNG);
//关闭摄像头
        webcam.close();

3. Summary

Here is a summary of my core code

This core code shows how to use Java to obtain a real-time camera to take pictures and save the image to a specified path.

  1. Get the default camera instance :
            Use the getDefault() method of the Webcam class to get the default camera instance.
  2. Set the image size captured by the camera :
            Use the webcam.setViewSize() method to set the image size captured by the camera to VGA (640x480).
  3. Create a WebcamPanel object:
           Create a WebcamPanel object and pass the camera instance to it to achieve the display of real-time images.
  4. Set the display of relevant information on the image panel:
            Use a series of methods of WebcamPanel to set the display of FPS, debugging information and image size on the image panel, and perform mirror display.
  5. Realize taking pictures and saving them:
           By calling the capture() method of WebcamUtils, passing the camera instance, saving path and image format as parameters, you can take pictures and save the images.
  6. Close the camera:
            Use the webcam.close() method to close the camera.

[Note] You need to import additional related libraries and tool classes, such as Webcam, WebcamPanel, WebcamResolution, WebcamUtils and ImageUtils. Through this code, you can achieve the function of obtaining the real-time camera to take pictures and save the images.

My sharing ends here. If you have any questions, you can discuss and communicate in the comment area! ! !

Guess you like

Origin blog.csdn.net/weixin_74383330/article/details/133297169