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.
PC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteWhat 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.
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Fix the driver behind crashes, sound loss and screen glitches3Clear out junk files and repair common Windows errorsChoose 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.
Rank #2
- 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.
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.
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.
Rank #4
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.writeto ensure an image writer was found. - Catch and report
IOExceptionfrom 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.
The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →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.
Best Value
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.
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.
Quick Recap
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.

