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 desktop pixels and javax.imageio.ImageIO to save them. Create a Robot, pass a positive-size screen-coordinate rectangle to createScreenCapture, then check the result of ImageIO.write. This works on a graphical desktop where the process has permission to read the screen; it does not work in a headless environment.

Capture a rectangle and save it as a PNG

This complete example captures a 1,280-by-720 region beginning at screen coordinate (0, 0) and writes it to screenshot.png in the program’s working directory. Adjust the rectangle to the screen area you need.

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();
        }
    }
}

Robot.createScreenCapture(Rectangle) reads pixels from the specified screen-coordinate rectangle and returns a BufferedImage. The rectangle’s width and height must both be greater than zero. Oracle’s Robot API documentation describes the result as an image containing pixels read from the screen.

ImageIO.write writes the image using a writer registered for the requested format. Its boolean result matters: false means no available writer supports that format. File errors can raise IOException, so handle it and make sure the destination directory is writable. Oracle’s ImageIO API documentation lists supported write methods.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

Choose the capture rectangle

The rectangle is in screen coordinates, not coordinates relative to a window. Its origin identifies the upper-left point of the capture region; its width and height determine the resulting image dimensions, subject to display scaling. A rectangle outside the actual screen area may fail or yield unusable pixels depending on the operating system and graphics environment. Use the reported device bounds when targeting a display instead of guessing coordinates.

Keep screen capture off the AWT event thread

Capturing can take time, particularly when the platform is waiting for permission to access display pixels. In a Swing application, do not perform the capture on the AWT Event Dispatch Thread (EDT), where a long operation can freeze window interaction. Run it on a worker thread or another background executor, then return to the EDT only for UI updates.

Capture the entire virtual desktop

For all connected displays, combine the bounds reported for each screen device. The resulting union covers the virtual desktop, including negative coordinate origins when a display sits left of or above the primary monitor.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
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 Exception {
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        Rectangle virtualBounds = null;

        for (GraphicsDevice device : ge.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 union may span the empty space between monitors if their layout is not contiguous. The output image therefore represents the full bounding rectangle, not a tightly packed collage of screen pixels. Its origin can be negative; do not replace the reported bounds with (0, 0) just because one monitor is designated primary.

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

Capture one specific monitor

Enumerate the devices, select the one you want, and use that device’s default configuration bounds. Construct Robot with the selected GraphicsDevice; this associates the robot with that device. The rectangle still comes from the device bounds, so it correctly reflects the display’s position in the graphics environment.

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 MonitorScreenshot {
    public static void main(String[] args) throws Exception {
        GraphicsDevice[] devices = GraphicsEnvironment
                .getLocalGraphicsEnvironment()
                .getScreenDevices();

        if (devices.length == 0) {
            throw new IllegalStateException("No screen devices found");
        }

        // Replace 0 with the index of the monitor to capture.
        int monitorIndex = 0;
        GraphicsDevice device = devices[monitorIndex];
        Rectangle bounds = device.getDefaultConfiguration().getBounds();

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

The device array’s ordering is supplied by the graphics environment; do not assume that a particular index always corresponds to a named physical monitor. Inspect each device’s bounds and, if necessary, let the user choose the intended display.

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Handle high-DPI and scaled displays

On a display whose user-space coordinates are scaled relative to its physical pixel resolution, createScreenCapture may not give the native-resolution image you expect. Java provides createMultiResolutionScreenCapture(Rectangle), which returns a MultiResolutionImage. Its variants include a base user-size image and, on high-resolution displays, a device-resolution image.

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

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

// Select the variant closest to the requested output dimensions.
BufferedImage image = capture.getResolutionVariant(2560, 1440);
boolean written = ImageIO.write(image, "png", new File("hi-dpi.png"));
if (!written) {
    throw new IOException("No writer available for PNG");
}

Choose the variant that matches the dimensions required by the next step in your workflow. A larger native-resolution image preserves more display detail but also uses more memory and produces a larger file. The available variants depend on the display and platform; inspect the returned image variants when exact dimensions matter. The Robot API documents the multi-resolution capture method.

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

Select an image format and output destination

PNG is a sensible default for desktop captures because it preserves pixels without lossy compression. To use another available writer, change the format string and file extension together, for example from "png" and screenshot.png to "jpeg" and screenshot.jpg. JPEG is lossy, so fine text and interface edges may look less crisp.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

ImageIO.write can write to a File, an OutputStream, or an ImageOutputStream. The latter options are useful when the image must go to a network stream or another destination rather than a local file. Regardless of destination, handle I/O failures and check the boolean return value. To verify that a saved file is readable, ImageIO.read(File) decodes it back into a BufferedImage; a null result indicates no registered reader could decode the input.

Requirements, permissions, and safe operation

  • A headed graphical session: a desktop environment must be available. Server processes and containers commonly run without one; check GraphicsEnvironment.isHeadless() before attempting capture.
  • Screen-capture permission: operating-system or desktop privacy controls can deny access to display pixels. Depending on the platform, a permission prompt or approval may be required. A denial can produce a SecurityException or unusable output.
  • A valid rectangle: width and height must be positive. When capturing a monitor or multi-monitor desktop, derive the rectangle from GraphicsDevice bounds.
  • Background execution: capture away from the AWT EDT, especially when it is important that the application remain responsive.
  • Writable output: ensure the process can create or overwrite the requested destination file, and handle IOException.

A screenshot can contain private messages, account details, or other sensitive data. Treat the captured image like any other sensitive file: limit who can read it, avoid logging its contents, and remove it when it is no longer needed.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshoot common Java screenshot failures

Symptom or exception Likely cause What to do
AWTException while creating Robot The platform cannot create a robot; a headless environment is a common cause. Run the program in a graphical desktop session. Check GraphicsEnvironment.isHeadless() first. Oracle documents that this exception is always thrown when GraphicsEnvironment.isHeadless() returns true.
SecurityException or blank/undefined pixels The desktop environment has not granted display-pixel access, or its security policy blocks it. Review the operating system’s screen recording/privacy permissions, grant access to the Java runtime if appropriate, then retry in the approved session.
IllegalArgumentException The rectangle has a zero or negative width or height. Validate that both dimensions are positive before calling createScreenCapture.
Wrong monitor, clipped output, or unexpected empty bands The rectangle assumed the primary display begins at (0, 0), or the virtual desktop includes gaps between monitors. Read each GraphicsDevice configuration’s bounds; use the selected device bounds for one monitor or their union for the virtual desktop.
Image looks soft or has fewer pixels than expected The capture uses the base user-size variant on a scaled display. Use createMultiResolutionScreenCapture and select the native-resolution variant if the workflow needs physical-pixel detail.
No file appears or it is empty The destination is unwritable, an I/O error occurred, or no writer supports the chosen format. Check the destination path and permissions, catch IOException, and check whether ImageIO.write returned false.
Application window freezes during capture The capture is running on the AWT Event Dispatch Thread, or the platform is taking time to authorize capture. Move the operation to a background thread and update Swing components on the EDT after it completes.

Or skip the browser setup

Java’s Robot captures a local desktop. If what you need is a screenshot of a website, ScreenshotNeo offers a one-request API instead. Its screenshot API and MCP server are made by Yorker Media. This example requests a WebP image of Stripe; replace the URL with the page you need and keep your API key private. See the ScreenshotNeo documentation for request details.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
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 are accepted and more than 60 known consent platforms, newsletter popups, and chat widgets are removed before capture; each step can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and responses include X-Page-Verdict and X-Billed headers. AI agents can use its MCP server tools, including take_screenshot, get_page_info, and capture_pdf. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000 screenshots. Visit ScreenshotNeo for product details, or sign up free for 1,000 screenshots a month with no card.

FAQ

Can Java take a screenshot without an external library?

Yes. The Java standard desktop APIs Robot and ImageIO are sufficient for screen capture and image-file output.

Can Java save a screenshot as a PDF?

The method shown here writes image formats through ImageIO; it does not create a PDF. A PDF requires a separate PDF-writing approach or library.

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.

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