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.

You do not need java.awt.Robot to save a Selenium browser image. Selenium exposes the TakesScreenshot interface: cast the driver, request OutputType.FILE, and copy the temporary file to a path you control. Use BYTES when you want Java to write the image directly, or BASE64 when another system expects text.

The direct Java solution

The following utility creates its destination directory, captures the current browser viewport, and copies Selenium’s temporary PNG to a durable location. It uses only Java NIO for persistence, so Apache Commons IO is not required.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;

public final class SeleniumShots {
    private SeleniumShots() { }

    public static Path save(WebDriver driver, Path destination) throws IOException {
        Path parent = destination.toAbsolutePath().getParent();
        if (parent != null) {
            Files.createDirectories(parent);
        }

        Path temporary = ((TakesScreenshot) driver)
                .getScreenshotAs(OutputType.FILE)
                .toPath();

        return Files.copy(
                temporary,
                destination,
                StandardCopyOption.REPLACE_EXISTING);
    }
}

Call it after your driver has navigated to the state you want to preserve:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Path saved = SeleniumShots.save(driver, Path.of("screenshots/checkout.png"));
System.out.println("Saved to " + saved.toAbsolutePath());

OutputType.FILE gives you a temporary file. Selenium documents that this file is deleted when the JVM exits, so copy it immediately rather than storing its path for later. The basic driver screenshot represents the browser’s current capture scope; exact behavior is driver-dependent.

#1 Best Overall
Screen recorder software for PC – record videos and take screenshots from your computer screen – compatible with Windows 11, 10, 8, 7
  • Record videos and take screenshots of your computer screen including sound
  • Highlight the movement of your mouse
  • Record your webcam and insert it into your screen video
  • Edit your recording easily
  • Perfect for video tutorials, gaming videos, online classes and more

Why Robot is the wrong layer for a WebDriver screenshot

Robot captures pixels from the operating-system desktop. That makes the result depend on window focus, screen resolution, display scaling, remote-desktop sessions, and whether another window covers the browser. Selenium’s interface captures the WebDriver-controlled browser instead, so your test does not need a visible desktop or keyboard and mouse simulation.

Selenium’s API describes TakesScreenshot as an interface for a driver or HTML element that can capture a screenshot in different representations. Implementations include common drivers such as ChromeDriver, EdgeDriver, FirefoxDriver, InternetExplorerDriver, RemoteWebDriver, and SafariDriver, but support still depends on the Selenium, browser, and driver versions installed in your project. Check the API for your version when a cast or capability is unavailable.

Choose the output representation

The Java OutputType reference documents three useful forms. Select the one that matches what your test pipeline needs.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Output type Best use Persistence responsibility
FILE A conventional screenshot file that another API can copy Selenium creates a temporary file; copy it before the JVM exits
BYTES Writing the image with Java NIO, uploading it, or attaching it to a test report Your code writes or transfers the returned byte array
BASE64 Embedding an image in HTML or sending it through a text-only channel Your code decodes or renders the Base64 text at the destination

Write PNG bytes directly

This version avoids Selenium’s temporary-file lifecycle. It still creates the parent directory and replaces an existing file deliberately.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;

public static Path saveBytes(WebDriver driver, Path destination) throws IOException {
    Path parent = destination.toAbsolutePath().getParent();
    if (parent != null) {
        Files.createDirectories(parent);
    }
    byte[] png = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
    Files.write(png == null ? destination : destination, png,
            StandardOpenOption.CREATE,
            StandardOpenOption.TRUNCATE_EXISTING,
            StandardOpenOption.WRITE);
    return destination;
}

The conditional expression above is unnecessary for normal Selenium behavior; a clearer production version is simply Files.write(destination, png, ...). It is shown only to emphasize that the returned value is the image data your code must persist. Use the simpler form in your project:

byte[] png = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
Files.write(destination, png,
        StandardOpenOption.CREATE,
        StandardOpenOption.TRUNCATE_EXISTING,
        StandardOpenOption.WRITE);

Get Base64 for an HTML report

String image = ((TakesScreenshot) driver)
        .getScreenshotAs(OutputType.BASE64);
String dataUri = "data:image/png;base64," + image;

Do not write the Base64 string as though it were binary PNG data. Keep it as text for a report, or decode it before saving an image file.

Capture one element instead of the whole driver

A WebElement can expose the same screenshot capability. This is useful for a component-level regression artifact rather than a viewport image.

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.
Rank #2
MixPad Multitrack Recording Software for Sound Mixing and Music Production Free [Mac Download]
  • Mix an audio, music and voice tracks
  • Record single or multiple tracks simultaneously
  • Intuitive tools to split, trim, join, and many other editing features
  • Loaded with audio effects including EQ, compression, reverb, and more.
  • Load an audio file and export to all popular audio formats from studio quality wav to high compression formats
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebElement;

WebElement invoice = driver.findElement(By.cssSelector("#invoice"));
File temporary = invoice.getScreenshotAs(OutputType.FILE);
Path destination = Path.of("screenshots/invoice.png");
Path parent = destination.toAbsolutePath().getParent();
if (parent != null) {
    Files.createDirectories(parent);
}
Files.copy(temporary.toPath(), destination,
        StandardCopyOption.REPLACE_EXISTING);

Element screenshots are implementation-dependent, particularly with drivers that do not fully conform to the W3C WebDriver behavior. If the captured extent is wrong or the call is unsupported, verify the exact Selenium and driver versions and fall back to a driver screenshot plus cropping in your image pipeline.

Full-page screenshots are a separate capability

The ordinary getScreenshotAs call should not be treated as a universal full-page operation. Selenium’s Java API exposes a distinct full-page method through the Firefox driver and HasFullPageScreenshot. Use it only when your installed Firefox driver provides that method.

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.firefox.FirefoxDriver;

FirefoxDriver firefox = (FirefoxDriver) driver;
File temporary = firefox.getFullPageScreenshotAs(OutputType.FILE);
Path destination = Path.of("screenshots/page-full.png");
Path parent = destination.toAbsolutePath().getParent();
if (parent != null) {
    Files.createDirectories(parent);
}
Files.copy(temporary.toPath(), destination,
        StandardCopyOption.REPLACE_EXISTING);

Full-page capture can produce a much larger image than a viewport shot. Allow more memory and storage, and use a unique destination when tests run in parallel.

Make capture deterministic in tests

Wait for the state you intend to document

A screenshot records the rendered state at the instant Selenium captures it. Wait for a meaningful condition instead of inserting an arbitrary sleep: for example, wait for a result element to be visible, a loading marker to disappear, or a specific URL to be reached. If images are lazy-loaded, scroll or wait until the required content is present before capturing.

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

Use predictable, collision-free paths

  • Include the test name, browser, and a timestamp or UUID in the filename when workers run concurrently.
  • Create the parent directory before capture and ensure the CI user can write to it.
  • Use a .png extension for Selenium’s normal screenshot output.
  • Decide explicitly whether an existing file should be replaced; REPLACE_EXISTING does so.
  • Publish the directory as a CI artifact after the test, not only in the test workspace.

Keep the driver lifecycle separate from file persistence

Copy or write the screenshot before calling driver.quit(). A driver failure can prevent capture, but once the image has been persisted your reporting code no longer depends on the browser process.

Troubleshooting

ClassCastException when casting to TakesScreenshot

The active driver does not expose the interface in that build, or the object being cast is not the WebDriver you think it is. Confirm the concrete driver class, align Selenium with the browser driver, and check the Java API for the installed version. Do not substitute Robot merely to hide a driver compatibility problem.

The file is missing after the test

FILE is temporary. If you saved only the temporary path, the JVM can remove it. Copy it immediately, or request BYTES and write the bytes yourself.

AccessDeniedException or a missing directory

Use an absolute or known workspace path, call Files.createDirectories for its parent, and verify the account running the test has write permission. Relative paths are resolved from the process working directory, which may differ in an IDE and CI.

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

The image is blank, incomplete, or shows a spinner

The browser was captured before the page reached the required state, or a navigation failed. Add an explicit wait for a stable element, inspect the current URL and page logs, and capture a diagnostic image only after the wait condition has been evaluated. A screenshot cannot recover content that never loaded.

Element capture is unsupported or clipped

Element screenshot behavior is best-effort and driver-dependent. Try a driver-level screenshot, verify the element is displayed and inside the expected frame, and check the installed browser and Selenium versions.

Full-page capture is unavailable

The basic screenshot method does not promise full-page output across browsers. Use the Firefox full-page API where supported, or capture sections and assemble them with a separate image tool.

Parallel tests overwrite one another

Generate unique names per test invocation, or give each worker its own output directory. This is a file-naming problem, not a reason to use desktop automation.

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

Performance and reliability considerations

Use viewport screenshots for routine assertions and diagnostics; they transfer less data than full-page images. Prefer BYTES when the next step is an upload or report attachment, because your code can stream or store the returned data without managing Selenium’s temporary file. Use FILE when an existing report library accepts a file path. For very tall pages, expect greater memory, transfer, and artifact-storage demands.

There is no universal browser/version compatibility matrix in the rolling Java API pages. Treat support as a capability to verify in the versions installed by your project, especially for element and full-page screenshots. Keep a small smoke test that captures one viewport image in the same CI environment as your complete suite.

Rank #4
DeskFX Free Audio Effects & Audio Enhancer Software [PC Download]
  • Transform audio playing via your speakers and headphones
  • Improve sound quality by adjusting it with effects
  • Take control over the sound playing through audio hardware

Or skip the browser setup

ScreenshotNeo is a website screenshot API and MCP server when you need an image of a URL rather than a stateful Selenium flow. It is a practical alternative because it removes cookie-consent banners, newsletter popups, and chat widgets before capture; bot checks, blank pages, failed loads, timeouts, and cache hits are not billed; and its MCP server lets Claude, Cursor, or another MCP client call screenshot tools directly.

One GET request returns PNG, JPEG, WebP, or a PDF. The API also supports full-page and element capture, device and viewport settings, custom CSS and JavaScript, waits, request blocking, headers and cookies, geolocation, signed links, asynchronous jobs, bulk capture, and a usage API. Every feature is included on every plan.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo documentation for request parameters and response headers.

import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

Responses identify the page verdict and billing status with X-Page-Verdict and X-Billed headers. The free plan includes 1,000 screenshots each month with no card; paid plans start at $5 for 3,000 screenshots, and yearly billing provides two months free. If you want URL screenshots without installing browsers or maintaining drivers, sign up for the free ScreenshotNeo plan.

Frequently Asked Questions

Is ScreenshotNeo suitable for a login flow or a test that clicks through several states?

No. Selenium remains the better fit when the capture depends on an authenticated session, clicks, typed input, or other stateful browser interactions. ScreenshotNeo is aimed at requesting a URL and receiving an image or PDF.

Can a remote Selenium session save screenshots locally?

Yes, when the remote driver exposes TakesScreenshot. The bytes or temporary file are returned to the test process, which must then write them to a path available in that process’s environment.

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

Should screenshot files be committed to the source repository?

Usually not. Store generated images as test artifacts or in an external report system, and keep only intentionally reviewed baseline images under version control.

Quick Recap

Bestseller No. 1
Screen recorder software for PC – record videos and take screenshots from your computer screen – compatible with Windows 11, 10, 8, 7
Screen recorder software for PC – record videos and take screenshots from your computer screen – compatible with Windows 11, 10, 8, 7
Record videos and take screenshots of your computer screen including sound; Highlight the movement of your mouse
$19.99
Bestseller No. 2
MixPad Multitrack Recording Software for Sound Mixing and Music Production Free [Mac Download]
MixPad Multitrack Recording Software for Sound Mixing and Music Production Free [Mac Download]
Mix an audio, music and voice tracks; Record single or multiple tracks simultaneously; Intuitive tools to split, trim, join, and many other editing features
Bestseller No. 4
DeskFX Free Audio Effects & Audio Enhancer Software [PC Download]
DeskFX Free Audio Effects & Audio Enhancer Software [PC Download]
Transform audio playing via your speakers and headphones; Improve sound quality by adjusting it with effects

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.