In Selenium Java, capture the current browser view with the TakesScreenshot interface, then choose whether Selenium returns a temporary file, raw bytes, or a Base64 string. For a persistent image, copy the temporary file to your own path before the JVM exits.
Basic driver screenshot
The smallest complete example navigates to a page, casts the driver to TakesScreenshot, requests OutputType.FILE, and copies the result to a permanent location. Selenium’s official Java example uses Apache Commons IO for the copy operation.
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class ScreenshotExample {
public static void main(String[] args) throws IOException {
WebDriver driver = new ChromeDriver();
try {
driver.get("https://example.com");
File temporary = ((TakesScreenshot) driver)
.getScreenshotAs(OutputType.FILE);
File destination = new File("./screenshots/home.png");
FileUtils.copyFile(temporary, destination);
System.out.println("Saved screenshot to " + destination.getAbsolutePath());
} finally {
driver.quit();
}
}
}
The capture call takes the browser’s current context. Call it after navigation and after any interaction or wait whose result you want to document. Create the destination directory yourself when necessary; FileUtils.copyFile can copy the file, but it does not make your test logic correct if the surrounding path or permissions are wrong.
Selenium’s TakesScreenshot API defines the screenshot entry point. OutputType.FILE is a temporary file, so copying it is essential when the image must survive the JVM process. Selenium’s API notes that supported drivers and remote-driver implementations can differ, and an unsupported implementation may throw UnsupportedOperationException or another WebDriverException.
Free tools Windows power users keep installed
One-click scans. No signup required.
#1 Best Overall
- Easily record quick videos of your screen and camera that offer the same connection as a meeting without the calendar wrangling
- Draw on your screen as you record video with customizable arrows, squares, and step numbers to emphasize important information
- Provide clear feedback and explain complex concepts with easy-to-use professional mark-up tools and templates
- Instantly create a shareable link where your viewers can leave comments and annotations or upload directly to the apps you use every day
- Version Note: This listing is for Snagit 2024. Please note that official technical support and software updates for this version are scheduled to conclude on December 31, 2026.
What OutputType should you use?
OutputType provides three documented representations. Select the one that matches the next operation rather than converting unnecessarily.
| Output | Java value | Use it when | Important behavior |
|---|---|---|---|
FILE |
File |
You need a normal image file for reports, artifacts, or manual inspection. | The returned file is temporary. Copy it to a controlled destination. |
BYTES |
byte[] |
You will upload, hash, transform, or attach the image in memory. | No intermediate file is required. |
BASE64 |
String |
An API, JSON document, or HTML report expects encoded text. | Decode it before treating it as binary image data. |
Save bytes directly
import java.nio.file.Files;
import java.nio.file.Path;
byte[] png = ((TakesScreenshot) driver)
.getScreenshotAs(OutputType.BYTES);
Files.write(Path.of("screenshots", "checkout.png"), png);
This approach avoids managing Selenium’s temporary file. The bytes are still whatever image format the driver supplies; use the filename and downstream MIME handling consistently with your driver configuration.
Embed or transmit Base64
String encoded = ((TakesScreenshot) driver)
.getScreenshotAs(OutputType.BASE64);
String dataUri = "data:image/png;base64," + encoded;
Use a data URI only where the receiving system accepts one. Base64 increases payload size compared with binary bytes, so bytes or a file are usually better for large artifacts.
Capture a particular element
Selenium also exposes screenshot behavior on WebElement. Locate the element, then request the same output forms:
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
import java.io.File;
import org.openqa.selenium.WebElement;
WebElement banner = driver.findElement(By.cssSelector("header"));
File temporary = banner.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(temporary, new File("./screenshots/header.png"));
An element capture targets the selected element rather than the complete current browsing context. Exact boundaries depend on the driver implementation. Selenium describes non-W3C-conformant implementations as best effort, so do not assume every browser or remote driver crops identical pixels.
Rank #2
- 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
Wait for the state you want to capture
A screenshot records the instant at which the command runs. Waiting for document navigation alone may be insufficient when the page renders asynchronously. Use an explicit wait for a visible or present element before capturing.
import java.time.Duration;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(15));
driver.get("https://example.com/account");
wait.until(ExpectedConditions.visibilityOfElementLocated(
By.cssSelector("main.account")));
File temporary = ((TakesScreenshot) driver)
.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(temporary, new File("./screenshots/account.png"));
For a stable test artifact, wait for the specific text, control, or state that proves the page is ready. A screenshot taken during a transition can be valid evidence of that transition but a poor visual regression baseline.
Full-page expectations and browser limits
The basic WebDriver screenshot call should not be described as a universally reliable full-page capture. The Java API specifies behavior according to implementation conformance; browsers and drivers can return different viewport or page boundaries. If you require a long-page image, verify the behavior of the exact browser, driver, and remote service you run, or use a capture service that exposes an explicit full-page option.
Viewport versus document size
- A normal driver screenshot commonly represents the visible browsing context, not every pixel below the fold.
- Element screenshots are limited to the element’s rendered bounds and are likewise implementation-dependent.
- Responsive output depends on window size, device emulation, zoom, and pixel ratio; set those deliberately in the test setup when they matter.
Reusable helper for test suites
Centralizing naming and error handling keeps test methods readable. This helper preserves the original exception while creating a timestamped artifact directory.
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
public final class Screenshots {
private Screenshots() {}
public static Path save(WebDriver driver, String name) throws IOException {
Path directory = Path.of("build", "screenshots");
Files.createDirectories(directory);
String stamp = LocalDateTime.now()
.format(DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss"));
Path target = directory.resolve(stamp + "-" + name + ".png");
File temporary = ((TakesScreenshot) driver)
.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(temporary, target.toFile());
return target;
}
}
In parallel tests, include a test identifier, browser name, or worker number in the filename to prevent two workers from overwriting the same artifact. Keep screenshot capture conditional if images are only needed after failures; unconditional captures add disk and transfer cost to every test.
Rank #3
- Screen capture software records all your screens, a desktop, a single program or any selected portion
- Capture video from a webcam, network IP camera or video input device
- Use video overlay to record your screen and webcamsimultaneously
- Intuitive user interface to allow you to get right to video recording
- Save your recordings to ASF, AVI, and WMV
Troubleshooting Selenium Java screenshots
ClassCastException or unsupported screenshots
The active driver may not implement TakesScreenshot, or a remote implementation may not expose the command. Use a driver documented as supporting screenshots and check the concrete driver/service configuration. Catch UnsupportedOperationException and WebDriverException at the test boundary when a screenshot is diagnostic rather than the assertion itself.
The file disappears or is empty
OutputType.FILE is temporary. Copy it immediately, before the JVM exits. Check that the destination directory exists and that the test process has write permission. For more predictable lifecycle handling, request BYTES and write them with Files.write.
Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Fix the driver behind crashes, sound loss and screen glitches3Repair Windows errors before they cause bigger problemsThe screenshot shows the wrong page or an overlay
Capture only after the navigation, click, animation, and asynchronous request that define the desired state. Add an explicit wait for a meaningful element. If a cookie dialog or modal is part of the current state, dismiss it before taking the image when the test’s purpose is the underlying page.
The image is cropped differently across browsers
Do not rely on undocumented full-page or element-boundary behavior. Pin compatible browser and driver versions in your test environment, set the viewport explicitly, and compare artifacts only within a controlled matrix.
Remote execution fails intermittently
Inspect the thrown WebDriverException, verify that the remote endpoint supports screenshots, and retain the browser logs and test URL as well as the image. A screenshot command cannot recover a crashed session; recreate the session according to your test runner’s retry policy.
Rank #4
- Capture video directly to your hard drive
- Record video in many video file formats including avi, wmv, flv, mpg, 3gp, mp4, mov and more
- Capture video from a webcam, network IP camera or a video input device (e.g.: VHS recorder)
- Screen capture software records the entire screen, a single window or any selected portion
- Digital zoom with the mouse scroll wheel, and drag to scroll the recording window
Or skip the browser setup
ScreenshotNeo is a website screenshot API and MCP server. One GET request returns a PNG, JPEG, WebP, or PDF, with options for full-page capture, lazy-loaded images, CSS-selector element capture, device and viewport settings, retina scale, waits, custom JavaScript and CSS, cookies and headers, blocking rules, geolocation, timezone, resizing, caching, signed links, asynchronous jobs, webhooks, bulk capture, and usage reporting. Its clean-shot workflow accepts consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be disabled.
Only clean shots are billed. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and response headers identify the page verdict and billing result.
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 authentication and options. An MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients.
There is a free allowance of 1,000 screenshots each month without a card. Paid plans start at $5 for 3,000 shots; every feature is available on every plan. Create a free ScreenshotNeo account.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.FAQ
Does Selenium save PNG automatically?
The driver returns the representation you request. With FILE, copy the temporary file to a path whose extension and downstream handling match your test artifact.
Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchWindows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallCan I take a screenshot after a failed assertion?
Yes, if the WebDriver session is still alive. Put the capture in a failure hook and handle screenshot errors separately so diagnostic collection does not hide the original test failure.
Best Value
- 【1080P HD High Quality】Capture resolution up to 1080p for video source and it is ideal for all HDMI devices such as PS4, PS3, Xbox One, Xbox 360, Wii U, DVDs, DSLR, Camera, Security Camera and set top box. Note: Video input supports 4K30/60Hz and 1080p120/144Hz. Does not support 4K120Hz/144Hz. Output supports up to 2K30Hz.
- 【Plug and Play】No driver or external power supply required, true PnP. Once plugged in, the device is identified automatically as a webcam. Detect input and adjust output automatically. Won't occupy CPU, optional audio capture. No freeze with correct setting.
- 【Compatible with Multiple Systems】suitable for Windows and Mac OS. High speed USB 3.0 technology and superior low latency technology makes it easier for you to transmit live streaming to Twitch, Youtube, Facebook, Twitter, OBS, Potplayer and VLC.
- 【HDMI LOOP-OUT】Based on the high-speed USB 3.0 technology, it can capture one single channel HD HDMI video signal. There is no delay when you are playing game live.
- 【Support Mic-in for Commentary】Rybozen capture card has microphone input and you can use it to add external commentary when playing a game. Please note: it only accepts 3.5mm TRS standard microphone headset.
Is a Base64 screenshot suitable for an API?
It is suitable when the API explicitly expects encoded text. Otherwise, send the raw byte[] or a file to avoid Base64 overhead.
Frequently Asked Questions
Does Selenium save PNG automatically?
The driver returns the representation you request. With FILE, copy the temporary file to a path whose extension and downstream handling match your test artifact.
Can I take a screenshot after a failed assertion?
Yes, if the WebDriver session is still alive. Put the capture in a failure hook and handle screenshot errors separately so diagnostic collection does not hide the original test failure.
Is a Base64 screenshot suitable for an API?
It is suitable when the API explicitly expects encoded text. Otherwise, send the raw byte[] or a file to avoid Base64 overhead.
The Bottom Line
Use TakesScreenshot.getScreenshotAs, copy OutputType.FILE immediately when you need a persistent artifact, and choose bytes or Base64 when the next step is in memory or over a text API. Treat full-page and element boundaries as driver-dependent.
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.

