Capture screenshots in java

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

CLI programme to take a screenshot

License

amiraslanaslani/java-screen-capture

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

CLI programme to take a screenshot. Currently you can set width, height and format (PNG, JPG, GIF) of captured screenshot. This programme is written in Java language and as a result this is a cross-platform programme.

usage: java -jar ScreenshotCapture.jar [options] Options: -s,--standardoutput Get screenshot in standard output stream -b,--base64 Get screenshot's encoded string in base64 -B,--bytes Get screenshot's byte array -e,--extension Set output file extension (png|jpg|gif) -h,--help Show help/usage -o,--output Set output file name -x,--width Set output width -y,--height Set output height 
  • If you don’t sets dimensions of screenshot then that saved in dimensions if your monitor.
  • If you don’t sets extension (with -e or —extension ) and output file (with -o and —output ) then set the extension to PNG by default.
Читайте также:  Java get all constructors

Capture a screenshot in dimensions of your monitor and save as example.jpg in JPG format:

java -jar ScreenshotCapture.jar -o example.jpg 

Capture a screenshot in 300 pixels width and save as example.png in PNG format:

java -jar ScreenshotCapture.jar -x 300 -s > example.png 

You can build programme easily with ant. Just install Ant and run ant command and JAR file is builded in /dist directory. If you want to develop this programme you should add Common CLI library to your project. (Jar files of Common CLI located at /libs directory)

Источник

Готовим screenshot с Java

Далее выложу рецепт для Java программы делающей снимок экрана.

  • Место, где сохранить снимок. Берем домашнюю директорию пользователя. Для Windows: это Desktop.
  • Знание размера экрана: Toolkit нам в помощь.
  • В общем-то, и все что нужно, приступаем.

В итоге получаем что то вроде:

package habra.screen; import java.io.File; import java.awt.Robot; import java.awt.Toolkit; import java.awt.Rectangle; import java.io.IOException; import java.awt.AWTException; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import javax.swing.filechooser.FileSystemView; public class App < public static void main(String[] args) < try < ImageIO.write(grabScreen(), "png", new File(getHomeDir(), "screen.png")); >catch (IOException e) < System.out.println("IO exception"+e); >> private static File getHomeDir() < FileSystemView fsv = FileSystemView.getFileSystemView(); return fsv.getHomeDirectory(); >private static BufferedImage grabScreen() < try < return new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize())) ; >catch (SecurityException e) < >catch (AWTException e) < >return null; > > 

Все помещается в App.java и жарится в командной строке:

SET proj=screen REM Delete classes dir RMDIR /S /Q classes mkdir classes REM Compiling javac -sourcepath src -d classes src\habra\%proj%\App.java mkdir jars del jars\%proj%.jar REM Making jar jar cfe jars\%proj%.jar habra.%proj%.App -C classes . 

Запускаем: java -jar jars\%proj%.jar

Раз два три! Вот и все! Берем снимок.

Источник

How to capture screenshot programmatically in Java

In this tutorial, we are going to show you how easy it is to capture a screenshot (either whole or partial) programmatically, and then saves the screenshot to an image file using Java API. The technique can be used to create screen video capture software.

1. About the Robot.createScreenCapture() and ImageIO.write() methods

The java.awt.Robot class provides a useful method for capturing a screenshot. Here’s the method signature:

BufferedImage createScreenCapture(Rectangle screenRect)

We pass a screen region (in rectangle) to be captured as this method’s parameter. The captured graphic is returned as a BufferedImage object which can be drawn onto a GUI component or saved to a file. And we use the ImageIO.write() static method to save the BufferedImage object to a file:

boolean write(RenderedImage im, String formatName, File output)

where the formatName can be “jpg”, “png”, “bmp”, etc.

Читайте также:  Css animation with example

NOTE: The captured image does not include the mouse cursor.

2. Capture full screen Java example

To capture a screenshot of the whole screen, we need to know the screen size. The following statement obtains the screen size as a Rectangle object:

Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
package net.codejava.graphics; 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; /** * This program demonstrates how to capture a screenshot (full screen) * as an image which will be saved into a file. * @author www.codejava.net * */ public class FullScreenCaptureExample < public static void main(String[] args) < try < Robot robot = new Robot(); String format = "jpg"; String fileName = "FullScreenshot." + format; Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()); BufferedImage screenFullImage = robot.createScreenCapture(screenRect); ImageIO.write(screenFullImage, format, new File(fileName)); System.out.println("A full screenshot saved!"); >catch (AWTException | IOException ex) < System.err.println(ex); >> >

3. Capture a portion of the screen Java example

To capture screenshot of a portion of the screen, we need to specify a rectangle region to be captured. For example, the following statements create a capture region which is the first quarter of the screen (suppose that the screen is divided into four parts):

Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Rectangle captureRect = new Rectangle(0, 0, screenSize.width / 2, screenSize.height / 2);
package net.codejava.graphics; import java.awt.AWTException; import java.awt.Dimension; 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; /** * This program demonstrates how to capture screenshot of a portion of screen. * @author www.codejava.net * */ public class PartialScreenCaptureExample < public static void main(String[] args) < try < Robot robot = new Robot(); String format = "jpg"; String fileName = "PartialScreenshot." + format; Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Rectangle captureRect = new Rectangle(0, 0, screenSize.width / 2, screenSize.height / 2); BufferedImage screenFullImage = robot.createScreenCapture(captureRect); ImageIO.write(screenFullImage, format, new File(fileName)); System.out.println("A partial screenshot saved!"); >catch (AWTException | IOException ex) < System.err.println(ex); >> >

4. Capture a GUI component Java example

Capturing screenshot of a GUI component (e.g. buttons, text fields, windows, etc) is even easier as we don’t have to use the Robot class. Each Swing component has a paint() method which can be used to paint a Graphics object. The following method will capture image of an arbitrary component and save it to an image file:

void captureComponent(Component component) < Rectangle rect = component.getBounds(); try < String format = "png"; String fileName = component.getName() + "." + format; BufferedImage captureImage = new BufferedImage(rect.width, rect.height, BufferedImage.TYPE_INT_ARGB); component.paint(captureImage.getGraphics()); ImageIO.write(captureImage, format, new File(fileName)); System.out.printf("The screenshot of %s was saved!", component.getName()); >catch (IOException ex) < System.err.println(ex); >>

Component GUI capture demo

Click the Capture Me! button, its image will be saved as the button1.png file which looks like this:

button1

And click the Capture This Frame! button, image of the frame’s content will be saved as the frame0.png file which looks like this:

Читайте также:  Javascript dom set style

frame0

API References:

Other Java Graphics Tutorials:

About the Author:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

Источник

Take a Screenshot in Java and save as PNG/JPG

A screenshot, screen capture, screen cap, screen dump, or screengrab is a visual snapshot in time of the monitor, television, or other visual output device in use. In the following tutorial, we demonstrate how to capture a screenshot in Java and save it as a PNG/JPG. The first example show how to capture a fullscreen screen capture. The second example shows how to capture a partial screen dump. These examples only work when you are running a desktop application. You can also capture screenshots of a web page using selenium, which is explained in my other tutorial.

The java.awt.Robot class is used to generate native system input events for the purposes of test automation, self-running demos, and other applications where control of the mouse and keyboard is needed. The primary purpose of Robot is to facilitate automated testing of Java platform implementations.

Take Fullscreen Screenshot

The Toolkit.getDefaultToolkit().getScreenSize() gets the dimensions of the screen. We use these dimensions to create a java.awt.Rectangle instance. We create a new instance of the java.awt.Robot class and call the createScreenCapture() method and pass the perviously created rectangle instance as the argument. This creates a BufferedImage , which we pass as the first argument in the ImageIO.write() method. The second argument we pass in the file format. In the third and last argument, we pass an FileOutputStream that’ll write the image to disk.

package com.memorynotfound.awt; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.FileOutputStream; import java.io.IOException; public class FullScreen < public static void main(String. args) throws AWTException, IOException < Rectangle screenRectangle = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()); BufferedImage image = new Robot().createScreenCapture(screenRectangle); ImageIO.write(image, "png", new FileOutputStream("/tmp/full-screen.png")); >>

Capture Partial Screenshot

You can also take a partial screenshot. For this you need to know the exact dimensions.

package com.memorynotfound.awt; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.FileOutputStream; import java.io.IOException; public class PartialScreen < public static void main(String. args) throws AWTException, IOException < Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Rectangle screenRectangle = new Rectangle(0, 0, screenSize.width/2, screenSize.height/2); BufferedImage image = new Robot().createScreenCapture(screenRectangle); ImageIO.write(image, "png", new FileOutputStream("/tmp/partial-screen.png")); >>

References

Источник

Оцените статью