Skip to content
Related Articles

Related Articles

Java Program to Take a Snapshot From System Camera
  • Last Updated : 11 Feb, 2021

It is better to have a brief knowledge of the Swing class of java as it is applied in the implementation to do so as whenever there arises a need to deal with images or dealing with the two-dimensional matrix as an output or usage of it in generating the output in java, Swing class comes into play in achieving the same.

We will be using Netbeans IDE o create GUI applications since it is a well crafted open-source IDE that provides features of a component inspector, Drag-and-Drop of widgets, Debugger, Object browser, etc and there is no need to import JAR files unlikely as seen in other IDEs such as an eclipse. Now this gives this IDE an extra edge over the other IDEs.

Concept:

Basically, this program is divided into 2 parts. One is the design part which is done using swing controls. And the other part is some code part to capture image.

  1. In the design part, I have used swing controls to design the interface. We just need to drag and drop the controls from palette. Here 2 labels and 1 button are used. The first label name is ‘lblclose‘. There I have set a PNG image and written a code on events-> action performed. When you click on that image the output window will close. For this, I have used dispose() method. The second label name is ‘lblphoto’. Here you can see your image when you run the program. The webcam will open when you run your code. Here I have used one button named ‘btnclick. You can see a button CLICK. When you click on the button the image will be captured in your ‘lblphoto‘ label.
  2. In the code part, I have used Webcam be named it ‘wc’ ie created a webcam object. The library allows you to use your build-in or external webcam directly from Java. It’s designed to abstract commonly used camera features and support multiple capturing frameworks. Then by open() function, the webcam will open. Then after clicking on the CLICK button you will capture an image. Then convert this image according to the size of the label. Then assign this image to label. Then create and start the thread.

 Procedure:



  1. Creation of a new java application and further creating a file under the project.`
  2. Start dragging toolkit widgets as per need from the palette situated on top-right.
  3. Click anywhere on the panel area and go to properties to change the background.
  4. Now double-click on the background area and select any color of choice and press the Ok button.
  5. Now start dragging widgets on the drawing area.
  6. Start writing the java program as explained below.
  7. Select the JAR files as in libraries JAR files need to be imported.

Implementation:

Step 1(a): Create a new Java application by clicking on ‘New Project → Java → Java Application‘ and give a suitable project name. Considering a random example for illustration purposes ‘MyFirstFrame’ and click Finish.

Step 1(b): To create a ‘New File’ under the same Java project ‘MyFirstFrame’, right-click on the project name on the left-hand side of the window, click as below shown, and click finish. E.g. MyFrame.java

New -> JFrame Form and give a suitable file name

Step 2: Now from the palette situated at the right-hand side of the window, start dragging the toolkit widgets as per requirements. To change the background color of the frame, we need to first insert a JPanel and change its properties.

Step 3: Click anywhere on the panel area, go to ‘properties → background.’

Step 4: Double-click on the background option and select any color of the desired choice meeting requirement choice and click OK.



Step 5: After setting the background color, drag other widgets onto the design area. Here I have dragged a button and a label. Button named CLICK and label is used to capture an image. In addition, a border is given to the label.

Step 6(a): Now write the code by right-clicking as shown below 

MyFrame.java → Split → Horizontally

Step 6(b): Then this pop-up window will appear. Here click on ‘source to write the code, and further one can click on ‘designto move to design.

Step 7(a): Adding up the jar files, go to Libraries. Right-click on ‘libraries‘ and select ‘ADD JAR/FOLDER‘. 

Step 7(b): Select the 3 jar files, then click on ‘open‘. The requirements are as follows as in libraries JAR files need to be imported more specifically 3 JAR files need to be import

  • bridj-0.7.0.jar
  • slf4j-api-1.7.2.jar
  • webcam-capture-0.3.12.jar

Implementation:

The sample input image is as shown below:

Example:

Java




// Java Program to Take a Snapshot From System Camera
  
package myfirstform;
  
// The goal of this import com.github.sarxos.webcam.Webcam
// is to allow integrated or USB-connected webcams
// to be accessed directly from java
// Using provided libraries users are able to
// read camera images and detect motion
import com.github.sarxos.webcam.Webcam;
  
// Provides classes for creating and modifying images*/
import java.awt.Image;
  
// Creates an ImageIcon from an array of bytes
// which were read from an image file containing
// a supported image format, such as GIF, JPG, PNG
import javax.swing.ImageIcon;
  
// Class
// Main class 
public class MyFrame
    extends javax.swing.JFrame implements Runnable {
  
    // Creates new form MyFrame
    public MyFrame()
    {
  
        // Initialising the components
        initComponents();
  
        // This is for the closing button
        lblclose.setText("");
  
        // Createing an image icon by adding path of image
        ImageIcon img = new ImageIcon(
            "C:\\Users\\dhannu\\Documents\\NetBeansProjects\\MyFirstForm\\src\\images\\sf.png");
  
        // Creating an object of Image type
        Image myimg = img.getImage();
  
        // Creating a new image whose size is same as label
        // size using algorithm - SCALE_SMOOTH
        Image newimage = myimg.getScaledInstance(
            lblclose.getWidth(), lblclose.getHeight(),
            Image.SCALE_SMOOTH);
  
        // Creating a image icon from new image
        ImageIcon ic = new ImageIcon(newimage);
  
        // Assigning the imageicon to the label
        lblclose.setIcon(ic);
  
        // Thread is created and started using
        // start() method which begins thread execution
        new Thread(this).start();
    }
    // generated code
      
    // This method is called from within the constructor to
    // initialize the form. WARNING: Do NOT modify this
    // code. The content of this method is always
    // regenerated by the Form Editor.
      
    @SuppressWarnings("unchecked")
   
    private void initComponents()
    {
  
        jPanel1 = new javax.swing.JPanel();
        lblclose = new javax.swing.JLabel();
        lblphoto = new javax.swing.JLabel();
        btnclick = new javax.swing.JButton();
  
        setDefaultCloseOperation(
            javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setUndecorated(true);
  
        // Setting the background by providing
        // Custom input bounds as parameters
        jPanel1.setBackground(
            new java.awt.Color(204, 204, 255));
  
        lblclose.addMouseListener(
            new java.awt.event.MouseAdapter() {
                public void mouseClicked(
                    java.awt.event.MouseEvent evt)
                {
                    lblcloseMouseClicked(evt);
                }
            });
  
        lblphoto.setBorder(
            javax.swing.BorderFactory.createLineBorder(
                new java.awt.Color(0, 0, 0), 4));
  
        // Click button
        btnclick.setText("CLICK");
  
        btnclick.addActionListener(
            new java.awt.event.ActionListener() {
                public void actionPerformed(
                    java.awt.event.ActionEvent evt)
                {
                    btnclickActionPerformed(evt);
                }
            });
  
        javax.swing.GroupLayout jPanel1Layout
            = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout
                .createParallelGroup(javax.swing.GroupLayout
                                         .Alignment.LEADING)
                .addGroup(
                    jPanel1Layout.createSequentialGroup()
                        .addGap(51, 51, 51)
                        .addComponent(
                            lblphoto,
                            javax.swing.GroupLayout
                                .PREFERRED_SIZE,
                            143,
                            javax.swing.GroupLayout
                                .PREFERRED_SIZE)
                        .addPreferredGap(
                            javax.swing.LayoutStyle
                                .ComponentPlacement.RELATED,
                            34, Short.MAX_VALUE)
                        .addComponent(
                            lblclose,
                            javax.swing.GroupLayout
                                .PREFERRED_SIZE,
                            28,
                            javax.swing.GroupLayout
                                .PREFERRED_SIZE)
                        .addContainerGap())
                .addGroup(
                    jPanel1Layout.createSequentialGroup()
                        .addGap(97, 97, 97)
                        .addComponent(btnclick)
                        .addContainerGap(
                            javax.swing.GroupLayout
                                .DEFAULT_SIZE,
                            Short.MAX_VALUE)));
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout
                .createParallelGroup(javax.swing.GroupLayout
                                         .Alignment.LEADING)
                .addGroup(
                    jPanel1Layout.createSequentialGroup()
                        .addGroup(
                            jPanel1Layout
                                .createParallelGroup(
                                    javax.swing.GroupLayout
                                        .Alignment.LEADING)
                                .addGroup(
                                    jPanel1Layout
                                        .createSequentialGroup()
                                        .addContainerGap()
                                        .addComponent(
                                            lblclose,
                                            javax.swing
                                                .GroupLayout
                                                .PREFERRED_SIZE,
                                            28,
                                            javax.swing
                                                .GroupLayout
                                                .PREFERRED_SIZE))
                                .addGroup(
                                    jPanel1Layout
                                        .createSequentialGroup()
                                        .addGap(22, 22, 22)
                                        .addComponent(
                                            lblphoto,
                                            javax.swing
                                                .GroupLayout
                                                .PREFERRED_SIZE,
                                            143,
                                            javax.swing
                                                .GroupLayout
                                                .PREFERRED_SIZE)))
                        .addGap(18, 18, 18)
                        .addComponent(btnclick)
                        .addContainerGap(29,
                                         Short.MAX_VALUE)));
  
        javax.swing.GroupLayout layout
            = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout
                .createParallelGroup(javax.swing.GroupLayout
                                         .Alignment.LEADING)
                .addComponent(
                    jPanel1,
                    javax.swing.GroupLayout.PREFERRED_SIZE,
                    javax.swing.GroupLayout.DEFAULT_SIZE,
                    javax.swing.GroupLayout
                        .PREFERRED_SIZE));
        layout.setVerticalGroup(
            layout
                .createParallelGroup(javax.swing.GroupLayout
                                         .Alignment.LEADING)
                .addComponent(
                    jPanel1,
                    javax.swing.GroupLayout.PREFERRED_SIZE,
                    javax.swing.GroupLayout.DEFAULT_SIZE,
                    javax.swing.GroupLayout
                        .PREFERRED_SIZE));
  
        pack();
        setLocationRelativeTo(null);
    }
    // End of generate code
  
    private void
    lblcloseMouseClicked(java.awt.event.MouseEvent evt)
    {
  
        // Settimg flag as false to stop the thread
        // so that you can capture the snapshot
        flag = false;
  
        // Destroying and cleaning the JFrame window
        // by the operating system\
        // using dispose() method
        dispose();
    }
  
    private void
    btnclickActionPerformed(java.awt.event.ActionEvent evt)
    {
  
        flag = false;
    }
  
    // Main driver method
    public static void main(String args[])
    {
        // Set the Nimbus look and feel 
        // If Nimbus(Java 6+) is not available
        // stay with the default look and feel.
  
        // Try block to check if any exceptions occur
        try {
  
            for (javax.swing.UIManager
                     .LookAndFeelInfo info :
                 javax.swing.UIManager
                     .getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(
                        info.getClassName());
                    break;
                }
            }
        }
  
        // Catch blocks to handle exceptions
  
        // First catch block to handle exception
        // if class is not found
        catch (ClassNotFoundException ex) {
            java.util.logging.Logger
                .getLogger(MyFrame.class.getName())
                .log(java.util.logging.Level.SEVERE, null,
                     ex);
        }
  
        // Second catch block to handle for exception
        // InstantiationException
        // In generic, this exception is thrown
        // rarely
        catch (InstantiationException ex) {
            java.util.logging.Logger
                .getLogger(MyFrame.class.getName())
                .log(java.util.logging.Level.SEVERE, null,
                     ex);
        }
  
        // 3rd catch block to handle
        // IllegalAccessException
        catch (IllegalAccessException ex) {
            java.util.logging.Logger
                .getLogger(MyFrame.class.getName())
                .log(java.util.logging.Level.SEVERE, null,
                     ex);
        }
  
        // 4th catch block to handle Swing class
        // UnsupportedLookAndFeelException
        catch (javax.swing
                   .UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger
                .getLogger(MyFrame.class.getName())
                .log(java.util.logging.Level.SEVERE, null,
                     ex);
        }
        //</editor-fold>
  
        // Create and display the form
        java.awt.EventQueue.invokeLater(new Runnable() {
            // Method run() which will later on
            // over-ridden
            public void run()
            {
                new MyFrame().setVisible(true);
            }
        });
    }
    // End of generated code
  
    // Declaring variables
    private javax.swing.JButton btnclick;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel lblclose;
    private javax.swing.JLabel lblphoto;
  
    Webcam wc;
  
    // Initially setting flag as true
    boolean flag = true;
  
    // Overriding the run() method as
    // created above already
  
    // @Override
    public void run()
    {
  
        // Creating a webcam object
        wc = Webcam.getDefault();
  
        // Method to open the camera
        wc.open();
  
        // Chcking condiion over flag which
        // holds true for boolean true as
        // above flag is declared true
        while (flag) {
            // An image is clicked
            Image img = wc.getImage();
  
            // Create a image whose size is same as label
            img = img.getScaledInstance(
                lblphoto.getWidth(), lblphoto.getHeight(),
                Image.SCALE_SMOOTH);
  
            // The clicked image is assigned to a Label
            lblphoto.setIcon(new ImageIcon(img));
  
            // Try block to check for thread exception
            try {
                // Putting the thread to sleap
                Thread.sleep(20);
            }
  
            // Catch block in there is some
            // mishappening while the thread is
            // put to sleep
            catch (InterruptedException e) {
            }
        }
    }
}

Output:

This is a snapshot captured from front camera where the code is compiled and run. It will differ with realtime basic what comes in front of front camera when the above same code is compiled and run again.

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :