Thursday, November 10, 2016

Take Snapshot from Webcam using Java in just 4 lines

Their are several library present on internet which can help you take snapshot. Most of these are very complex to implement.I saw a webcam library from http://webcam-capture.sarxos.pl/ which is surprisingly very simple. This program uses this library and captures snapshot from your webcam in just 4 lines.

Language Used:
Java

Code Location:
https://github.com/csanuragjain/recorder/tree/master/Webcam%20Snapshot

Steps:

1) Add below dependency to your pom.xml. Reference: http://webcam-capture.sarxos.pl/
   <dependency>  
        <groupId>com.github.sarxos</groupId>  
        <artifactId>webcam-capture</artifactId>  
        <version>0.3.10</version>  
        <scope>test</scope>  
   </dependency>  


2) Below is the program:
 package com.cooltrickshome;  
 import java.awt.Dimension;  
 import java.io.File;  
 import java.io.IOException;  
 import javax.imageio.ImageIO;  
 import com.github.sarxos.webcam.Webcam;  
 public class WebcamCapture {  
      /**  
       * @param args  
       * @throws IOException  
       */  
      public static void main(String[] args) throws IOException {  
           Webcam webcam = Webcam.getDefault();  
           webcam.setViewSize(new Dimension(640, 480));  
           webcam.open();  
           ImageIO.write(webcam.getImage(), "PNG", new File("picture.png"));  
           System.out.println("Snapshot taken from cam and stored at "+new File("").getAbsolutePath()+"\\picture.png");  
      }  
 }  

How it works:

1) First we make a webcam object.
2) We define the picture resolution which we want to take from webcam. In this I chose 640x480
3) We open the webcam using open function
4) getImage returns the image as BufferedImage so we use ImageIO class to write BufferedImage data into png file

Hope it helps :)

No comments:

Post a Comment