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

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

Use java.awt.Robot to capture screen pixels into a BufferedImage, then write the image with ImageIO. For the primary display, build a rectangle from Toolkit.getDefaultToolkit().getScreenSize(); for a specific monitor, use that device’s bounds and a device-specific Robot. Run the capture on a worker thread, not the AWT event-dispatch thread.

Capture the primary display and save it as PNG

This Java SE 25 example captures the primary display’s screen-coordinate rectangle and writes a PNG file. The output path must be writable; the method returns the path after the write completes.

import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.file.Path;
import javax.imageio.ImageIO;

public final class FullScreenCapture {
    public static Path capture(Path output) throws AWTException, IOException {
        if (GraphicsEnvironment.isHeadless()) {
            throw new IllegalStateException("A display is required for Robot screen capture");
        }
        Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
        if (size.width <= 0 || size.height <= 0) {
            throw new IllegalStateException("The primary display has invalid dimensions");
        }
        Rectangle screen = new Rectangle(0, 0, size.width, size.height);
        BufferedImage image = new Robot().createScreenCapture(screen);
        ImageIO.write(image, "png", output.toFile());
        return output;
    }
}

Call capture(Path.of("screen.png")) from an application worker thread. createScreenCapture(Rectangle) reads pixels in screen coordinates and returns a BufferedImage. The rectangle must have positive width and height. Oracle’s Java SE 25 Robot API documents the capture method and its exceptions.

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

What this captures

“Full-screen” here means the rectangular pixel area of the primary display, not just the currently focused application window. Other visible windows and desktop content within those bounds can therefore appear in the image. This API captures the desktop; it does not select an application window by title or process.

Capture a particular monitor

For a multi-monitor setup, enumerate screen devices, select the intended monitor, and use both its configuration bounds and a Robot constructed for that device:

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

public static Path captureMonitor(int monitorIndex, Path output)
        throws Exception {
    GraphicsDevice[] devices = GraphicsEnvironment
            .getLocalGraphicsEnvironment().getScreenDevices();
    if (monitorIndex < 0 || monitorIndex >= devices.length) {
        throw new IllegalArgumentException("No monitor at index " + monitorIndex);
    }
    GraphicsDevice device = devices[monitorIndex];
    Rectangle bounds = device.getDefaultConfiguration().getBounds();
    if (bounds.width <= 0 || bounds.height <= 0) {
        throw new IllegalStateException("The selected monitor has invalid bounds");
    }
    Robot robot = new Robot(device);
    BufferedImage image = robot.createScreenCapture(bounds);
    ImageIO.write(image, "png", output.toFile());
    return output;
}

In production code, narrow the broad throws Exception in this compact example to the exceptions your caller handles, including AWTException and IOException. The index is only an array position in the devices returned on that machine; do not assume a particular index always corresponds to a named physical monitor.

Coordinates can be negative

A monitor positioned left of or above the primary display can have a negative x or y origin. Use the bounds returned by getDefaultConfiguration().getBounds() as they are rather than replacing the origin with (0, 0). Multi-screen coordinate behavior can vary with display configuration, so confirm the returned bounds and verify the resulting image on the target desktop. The GraphicsConfiguration API and GraphicsDevice API expose the relevant display information.

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

Choose between logical-size and HiDPI capture

On a system with user-space/device-space scaling, a rectangle’s logical dimensions may not equal the monitor’s native pixel dimensions. Java 9 and later provide createMultiResolutionScreenCapture(Rectangle) for this situation. It returns a MultiResolutionImage with a base image at the requested user-space size and, when scaling applies, a native-resolution variant.

  • Choose the base variant when the saved image should have logical layout dimensions.
  • Choose the native-resolution variant when preserving the denser pixel output is the goal, such as for archival capture.

For example, after obtaining a multi-resolution capture, you can select a variant appropriate to the desired output dimensions and pass that RenderedImage to ImageIO.write:

import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.MultiResolutionImage;
import java.awt.image.RenderedImage;
import java.io.File;
import javax.imageio.ImageIO;

MultiResolutionImage capture = new Robot()
        .createMultiResolutionScreenCapture(screenBounds);
RenderedImage nativeVariant = capture.getResolutionVariant(
        screenBounds.width * scaleFactor,
        screenBounds.height * scaleFactor);
ImageIO.write(nativeVariant, "png", new File("screen-hidpi.png"));

Set scaleFactor based on the target display’s scaling and confirm the available variant dimensions on that platform; do not assume every monitor uses the same scale. The Java API describes this as a way to capture with a scaling transform between user and device space.

Write PNG, JPEG, or another supported image

PNG is a sensible default for screenshots because it is lossless and preserves sharp interface edges. ImageIO.write(image, "png", file) is the simplest save operation. The writer returns a boolean indicating whether an appropriate writer was found; production code should check it, because a missing writer means no format was written.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
boolean written = ImageIO.write(image, "png", output.toFile());
if (!written) {
    throw new IOException("No PNG writer is available");
}

JPEG can be useful when smaller files matter more than pixel-perfect text and edges, because it is lossy. Use a format name supported by an installed ImageIO writer. The API’s ImageIO.write writes the image to the specified file, but it does not create missing parent directories; create those separately when needed.

Keep screen capture off the UI thread

Screen capture is synchronous: the call does not return until it has obtained the pixels. Oracle recommends avoiding it on the AWT Event Dispatch Thread because capture can take a long time, particularly if permission approval requires user interaction. If called from a Swing or AWT event handler, a slow capture can make the interface appear frozen.

Use a worker executor and marshal only UI updates back to the event-dispatch thread. For example, the capture method above can be submitted to a single-thread executor; handle its completion or exception separately from the UI action. Do not block the EDT waiting for the future to finish.

Permissions, headless systems, and other failure cases

Headless environment

Check GraphicsEnvironment.isHeadless() before constructing Robot. A headless environment has no usable display, keyboard, or mouse; Robot construction throws AWTException in this case. A server process without an attached graphical desktop is not made capturable merely by running the Java code.

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

Desktop capture permission denied

Some operating systems or desktop configurations require screen-recording or display-read permission. Depending on the platform, denial can cause SecurityException or undefined image contents. Grant the relevant permission to the application or runtime and retry, then inspect the output rather than assuming that a returned image contains valid pixels. Oracle’s Robot API documents these permission-related possibilities.

Robot construction fails

new Robot() and new Robot(device) can throw AWTException when the platform does not allow the requested operation. Report the exception with enough context to identify whether the primary display or a specific device was selected. Do not swallow it and save a misleading empty file.

Invalid or stale bounds

A zero or negative rectangle size is invalid for screen capture. Validate width and height before calling the method. Display topology can also change while an application is running—for example, when a monitor is disconnected or resolution changes. Re-enumerate devices and recreate a device-specific Robot after a topology change rather than relying on an old coordinate assumption.

Output file missing or unexpectedly small

  • Confirm the output path is writable and its parent directory exists.
  • Check the boolean result from ImageIO.write to ensure an image writer was found.
  • Catch and report IOException from file creation or writing.
  • Open the image and verify its dimensions and contents; a successful method return is not a substitute for checking permissions or the selected screen rectangle.

Is the pointer included?

The Robot API does not give a universal guarantee that the mouse cursor is drawn into the returned image. Treat cursor inclusion as platform-dependent and test it in the desktop environment where the application will run if it matters to your use case.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

ScreenshotNeo for website captures

ScreenshotNeo is a different option when the target is a website rather than the pixels of a local desktop monitor: it is a website screenshot API and MCP server, not a replacement for capturing arbitrary desktop applications with Robot. One GET request can return PNG, JPEG, WebP, or PDF. Cookie/consent banners, newsletter popups, and chat widgets are removed before capture; bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients.

Or skip the browser setup

For a website screenshot, use the API instead of setting up a browser automation stack. The code and parameter details are in the ScreenshotNeo documentation.

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

Cookie banners, popups, and chat widgets are removed before the shot. Bot checks, blank pages, and failed loads are never billed. The MCP server lets AI agents take screenshots. The Free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000. Sign up for ScreenshotNeo’s free plan.

Frequently Asked Questions

Does Java Robot capture only the active application window?

No. The rectangle-based method captures pixels in screen coordinates, so it includes whatever is visible within the selected display area.

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

Can Java Robot take screenshots on a headless server?

No. Robot construction fails when the Java environment is headless; capture requires a permitted graphical display.

Can I capture a website with Robot without opening a desktop browser?

Robot captures screen pixels from a desktop display. For a website capture without desktop setup, use a website screenshot API such as ScreenshotNeo.

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.