Thursday, 31 March 2016

Single line Java Code to take screenshot

java code to take screenshots


How to take screenshot in Java



This is a very interesting program where you will be able to take screenshots
of you computer through a simple progam shown below.

Program 1:A short and simple version for testing....

package codermag.net;

import java.awt.*;
import java.io.*;
import javax.imageio.ImageIO;

public class ScreenshotGrabber {

 public static void main(String[] args) throws IOException,
   HeadlessException, AWTException {

  ImageIO.write(new Robot().createScreenCapture(new Rectangle(Toolkit
    .getDefaultToolkit().getScreenSize())), "jpg", new File(
    "D:/screenshot.jpg"));
 }

}



Output:
java code to take screenshots


Program 2:Coding standards followed with proper error handling

package codermag.net;

import java.awt.AWTException;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class ScreenshotGrabber {

 public static void main(String[] args) {

  try{
  Robot robot=new Robot();
  Rectangle rectangle=new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
  
  
  BufferedImage bufferedImage=robot.createScreenCapture(rectangle);
  ImageIO.write(bufferedImage, "jpg", new File("D:/screenshot.jpg"));
  }
  catch (IOException e) {
   e.printStackTrace();
  } catch (AWTException e) {
   e.printStackTrace();
  }
 }

}


Capture screen with variable/dynamic screen size

If you need to change the screen dimensions according to your wish than take a look at the
following code snippet. The method takes in the height and width of the screenshot to be taken.
Please note that the height and width cannot be 0, so proper exception handling must be implemented.


public void captureScreen(int height, int width) {

  Rectangle rectangle = new Rectangle();
  rectangle.setSize(height, width);

  try 
  {
   ImageIO.write(new Robot().createScreenCapture(rectangle), "jpg",
     new File("D:/screenshot.jpg"));
  } 
  catch (IOException e) {}
  catch (AWTException e) {}
 }



2 comments:

  1. Nice program dude.But can you provide how to resize the image ie.according to my wish I will take the imagesize(dynamically).

    ReplyDelete
    Replies
    1. @Kaushik, Thank you for the test case. It got overlooked.
      A new section has been added at the end of this article, for doing this.

      Delete

Coder Magnet
CoderMagnet is full of resources from our daily development activities. It has solutions for common problematic scenarios in technologies like Java 8, AEM, JCR and also occasionally gives you tips on Blogger as well.