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 which is surprisingly very simple. This program uses this library and captures snapshot from your webcam in just 4 lines.

Language Used:

Code Location:


1) Add below dependency to your pom.xml. Reference:

2) Below is the program:
 package com.cooltrickshome;  
 import java.awt.Dimension;  
 import javax.imageio.ImageIO;  
 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));  
           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 :)