October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
AWT Robot

How to Take Desktop Screenshots in Java

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Java’s built-in java.awt.Robot to capture pixels from a desktop screen, then save the resulting image with javax.imageio.ImageIO. The capture rectangle is in screen coordinates, so use the display’s reported bounds for monitors and multi-display setups instead of assuming every screen starts at (0, 0). A graphical desktop and permission to read its pixels are required.

Capture a screen area and save it as PNG

This standalone example captures a 1280-by-720 rectangle beginning at screen coordinate (0, 0) and writes screenshot.png to the program’s working directory. Change the rectangle to select a different area. Its width and height must both be positive, and the chosen area must correspond to the screen-coordinate space available to the process.

import java.awt.AWTException;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class Screenshot {
    public static void main(String[] args) {
        if (GraphicsEnvironment.isHeadless()) {
            throw new IllegalStateException("A graphical desktop is required");
        }

        Rectangle area = new Rectangle(0, 0, 1280, 720);
        try {
            Robot robot = new Robot();
            BufferedImage image = robot.createScreenCapture(area);
            boolean written = ImageIO.write(image, "png", new File("screenshot.png"));
            if (!written) {
                throw new IOException("No writer available for PNG");
            }
        } catch (AWTException | IOException | SecurityException ex) {
            ex.printStackTrace();
        }
    }
}

Compile and run it in a Java environment with access to a graphical desktop, for example with javac Screenshot.java followed by java Screenshot. The file is created relative to the process’s current working directory, not necessarily beside the source file. The program reports capture or file errors on the console; it does not silently treat a missing ImageIO writer as success.

Capture a selected region

To capture a portion of the screen, construct the rectangle with the desired screen-coordinate origin and dimensions. For example, new Rectangle(200, 100, 640, 480) selects a 640-by-480 region beginning at (200, 100). Coordinates are not relative to an application window: they refer to the display coordinate system. If the region is outside the screen’s usable bounds, the result may not match the intended crop; calculate it from the relevant display bounds and verify the saved image.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
Philips 24 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 241V8LB
  • CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
  • WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
  • A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents

Capture every attached monitor

For a screenshot spanning all attached displays, calculate the union of the bounds reported by the graphics environment and capture that rectangle. A secondary monitor positioned to the left or above the primary display may have a negative X or Y origin. Using the union preserves those origins; hard-coding a rectangle from (0, 0) can omit part of the desktop or include the wrong region.

import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class VirtualDesktopScreenshot {
    public static void main(String[] args)
            throws java.awt.AWTException, IOException {
        GraphicsEnvironment environment =
                GraphicsEnvironment.getLocalGraphicsEnvironment();
        Rectangle virtualBounds = null;

        for (GraphicsDevice device : environment.getScreenDevices()) {
            Rectangle bounds = device.getDefaultConfiguration().getBounds();
            virtualBounds = virtualBounds == null
                    ? new Rectangle(bounds)
                    : virtualBounds.union(bounds);
        }

        if (virtualBounds == null
                || virtualBounds.width <= 0
                || virtualBounds.height <= 0) {
            throw new IllegalStateException("No usable display bounds");
        }

        BufferedImage desktop = new Robot().createScreenCapture(virtualBounds);
        boolean written = ImageIO.write(desktop, "png", new File("desktop.png"));
        if (!written) {
            throw new IOException("No writer available for PNG");
        }
    }
}

The output includes the entire bounding rectangle. If the monitors are arranged with gaps, the union rectangle also spans those gaps; memory use follows the dimensions of that rectangle, not just the sum of the active display areas. For very large or unusually arranged display setups, check the resulting dimensions and memory needs before capturing.

Rank #2
Philips 22 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 221V8LB
  • CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
  • SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors

Capture one specific monitor

Choose a GraphicsDevice from GraphicsEnvironment.getScreenDevices(), then use that device both to create the Robot and to obtain the rectangle. This avoids accidentally treating a secondary monitor’s origin as though it were the primary display’s origin.

GraphicsEnvironment environment =
        GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] devices = environment.getScreenDevices();

int monitorIndex = 1; // Change to the desired index for this machine.
if (monitorIndex < 0 || monitorIndex >= devices.length) {
    throw new IllegalArgumentException("Monitor index is not available");
}

GraphicsDevice target = devices[monitorIndex];
Rectangle bounds = target.getDefaultConfiguration().getBounds();
Robot robot = new Robot(target);
BufferedImage image = robot.createScreenCapture(bounds);
boolean written = ImageIO.write(image, "png", new File("monitor.png"));
if (!written) {
    throw new IOException("No writer available for PNG");
}

Device ordering is supplied by the local graphics environment, so do not assume index 0 or 1 means a particular physical monitor across machines. Inspect each device’s bounds or configuration when choosing one programmatically. The target device’s bounds provide the capture rectangle, and the target-device Robot performs the capture.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Dell 24 Monitor - SE2426H - 23.8-inch FHD (1920x1080) 144Hz 1ms Display, in-Plane Switching (IPS) Technology, AMD FreeSync™, TÜV 3-Star 2X HDMI, Tilt
  • Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
  • Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
  • Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
  • In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
  • Ultra-thin bezels: Maximize your viewing experience with thin bezels.

Handle HiDPI displays

On displays using user-space-to-device-space scaling, ordinary createScreenCapture(Rectangle) may not be the right choice when the required output is at native device resolution. Java’s Robot.createMultiResolutionScreenCapture(Rectangle) returns a MultiResolutionImage that can include a base image at user-space dimensions and a higher-resolution variant on high-resolution displays.

import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.MultiResolutionImage;
import java.awt.image.BufferedImage;

Rectangle area = new Rectangle(0, 0, 1280, 720);
MultiResolutionImage capture = new Robot().createMultiResolutionScreenCapture(area);

// Select a variant whose pixel dimensions suit the output or next processing step.
for (java.awt.Image variant : capture.getResolutionVariants()) {
    System.out.println(variant.getWidth(null) + " x " + variant.getHeight(null));
}

Choose the resolution variant based on the dimensions needed downstream; do not assume the first image is the native-resolution one. If writing the selected result, convert or obtain it as a BufferedImage as needed and pass it to ImageIO.write. For a normal-resolution capture, use createScreenCapture and avoid the extra selection step.

Rank #4
Samsung 27" Essential S3 (S36GD) Series FHD 1800R Curved Computer Monitor
  • CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
  • SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
  • MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
  • KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
  • INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient

Choose an image format and handle the output

ImageIO.write accepts a rendered image, a format name, and a destination such as a File, OutputStream, or ImageOutputStream. PNG is a common choice for screenshots when lossless output matters. Use a format name supported by a registered writer in the running Java environment, and always inspect the method’s boolean result: false means no writer is available for the requested format. File creation or writing problems are reported as IOException.

File output = new File("captures", "screen.png");
File parent = output.getParentFile();
if (parent != null && !parent.isDirectory() && !parent.mkdirs()) {
    throw new IOException("Could not create output directory: " + parent);
}

boolean written = ImageIO.write(image, "png", output);
if (!written) {
    throw new IOException("No writer available for PNG");
}

You can read a saved image back with ImageIO.read(File), which returns a BufferedImage when a suitable reader can decode it. Keeping capture and file writing as separate steps makes it easier to distinguish a desktop-access problem from an output-path or image-writer problem.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Sale
Sceptre New 22-Inch Gaming Monitor, FHD 1080p, Up to 144Hz, HDMI, DisplayPort, Built-in Speakers, Machine Black (E225W-FW144 Series, 2026)
  • 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
  • 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
  • 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Runtime, performance, and reliability considerations

  • Run in a graphical session. AWT screen capture needs a desktop display. A server process or container without a graphical environment cannot produce a real desktop screenshot through Robot.
  • Keep capture off the AWT Event Dispatch Thread. Screen capture can take time, including while the platform obtains permission. In a GUI application, run it on a worker thread so the interface remains responsive.
  • Check permission and environment policy. Desktop security controls may deny display-pixel access or require approval. A denied request can raise SecurityException; permission behavior depends on the operating system and desktop environment.
  • Budget for image memory. A screenshot requires an in-memory image. Larger capture rectangles, full multi-monitor unions, and high-resolution variants increase memory use. Capture only the area needed when processing or retaining a full desktop image is unnecessary.
  • Save to a deliberate path. Relative paths resolve from the process working directory. Use an explicit destination and handle directory creation and write failures if the output must land in a known location.

Troubleshoot common capture failures

Symptom or exception Likely cause What to check
AWTException when constructing Robot The platform cannot create the screen-capture robot; this includes headless execution. Check GraphicsEnvironment.isHeadless() and run the program in a desktop session.
SecurityException or blank/undefined pixels The desktop environment or security policy denies pixel access, or required approval has not been granted. Review the operating system or desktop’s screen-capture permission settings, grant access if appropriate, then run the capture again.
IllegalArgumentException from capture The rectangle has a width or height that is not greater than zero. Validate positive dimensions before calling createScreenCapture.
Wrong monitor, clipped area, or shifted crop The code assumes the primary screen begins at (0, 0) or uses bounds from another device. Read bounds from the selected GraphicsDevice; for all displays, capture the union of reported bounds, including negative origins.
Image looks soft or has unexpected pixel dimensions The display is scaled and the base-resolution capture is being used where native resolution is needed. Use createMultiResolutionScreenCapture and select the variant with the dimensions appropriate for the output.
No image file, or the program says no writer is available The destination is unwritable, the output directory does not exist, an I/O error occurred, or no registered writer supports the format name. Check the destination and permissions, handle IOException, and test the return value from ImageIO.write.

Or skip the browser setup

Robot is the right built-in route for pixels on the computer’s desktop. If what you actually need is an image of a public or authenticated web page, ScreenshotNeo is a website screenshot API rather than a physical desktop capture tool. One GET request returns a screenshot or PDF; see the ScreenshotNeo API documentation for parameters and response details.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

ScreenshotNeo removes cookie and consent banners, newsletter popups, and chat widgets before the shot. Bot checks, blank pages, and failed loads are not billed. Its MCP server lets AI agents take screenshots, and the Free plan includes 1,000 shots a month with no card; paid plans start at $5 for 3,000 shots. These are website captures, not screenshots of your local monitor. Learn more at ScreenshotNeo, or sign up free for 1,000 screenshots a month with no card.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Read next

Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.