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.

Most Selenium Java failures named RasterFormatException come from cropping the wrong image rectangle. A driver screenshot normally contains the current viewport, while an element’s location may be expressed in document coordinates. Passing those coordinates directly to BufferedImage.getSubimage() can request pixels outside the decoded raster. The simplest fix, when your WebDriver implementation supports it, is to let Selenium capture the element:

File screenshot = element.getScreenshotAs(OutputType.FILE);

If your stack trace points inside Selenium rather than your own image code, first collect the complete exception, Selenium/browser/driver/Java versions, operating system, and a minimal reproducer; there is no evidence that one universal version upgrade fixes every implementation.

What RasterFormatException means

Java’s BufferedImage API throws RasterFormatException when a requested area is not fully contained in an image raster. It can also report incompatibility between a raster’s bands and the bands required by its color model. Therefore, an out-of-bounds crop is the leading explanation when the failing line is getSubimage or another rectangle operation, but it is not the only one.

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

Read the full stack trace before changing Selenium or a browser driver. The exact failing method tells you whether the problem is your crop calculation, image decoding/construction, or Selenium’s screenshot command.

Why manual element cropping fails

A common older pattern is:

  1. Capture the whole driver screenshot.
  2. Decode it with ImageIO.read.
  3. Read element.getLocation() and element.getSize().
  4. Call fullImage.getSubimage(x, y, width, height).

This assumes that WebDriver coordinates and screenshot pixels describe the same origin, viewport, and scale. They may not. An element below the visible viewport can have a document-level y value beyond the screenshot’s height. Scrolling can change the relationship again. Device-pixel scaling, browser zoom, and retina settings can also make CSS-pixel dimensions differ from bitmap pixels.

The Java containment rule is strict: x and y must be nonnegative, width and height must be positive, and the rectangle must satisfy x + width <= image.getWidth() and y + height <= image.getHeight().

Preferred fix: Selenium’s element screenshot API

Selenium’s Java screenshot API is designed for a driver or an HTML element. Use the element itself instead of taking a viewport image and guessing a crop:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import java.io.File;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebElement;

WebElement card = driver.findElement(By.cssSelector(".product-card"));
File temporaryShot = card.getScreenshotAs(OutputType.FILE);

This asks the WebDriver implementation to produce the element image in the coordinate system it supports. Implementations that do not support element screenshots may throw UnsupportedOperationException; screenshot failures can also appear as WebDriverException or a more specific screenshot exception. Handle those cases rather than assuming the API is universally implemented.

Choose an output type deliberately

Output type Use it when Lifecycle or handling
FILE You need an image file for another tool The returned file is temporary and is deleted when the JVM exits; copy it to a durable destination.
BYTES You will upload or process the image in memory Receives raw screenshot bytes without an intermediate file.
BASE64 You need to embed or transmit encoded data Receives the screenshot as a Base64 string.

Persisting a FILE result

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

File temporaryShot = card.getScreenshotAs(OutputType.FILE);
Path destination = Path.of("artifacts", "card.png");
Files.createDirectories(destination.getParent());
Files.copy(temporaryShot.toPath(), destination,
           StandardCopyOption.REPLACE_EXISTING);

Copy before the JVM exits if the image must survive the test run.

Safe manual cropping when element capture is unavailable

Manual cropping is still useful for custom post-processing or unsupported WebDriver implementations. Validate against the decoded screenshot, not the page’s dimensions.

import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import org.openqa.selenium.Point;
import org.openqa.selenium.Rectangle;

File viewportFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
BufferedImage viewport = ImageIO.read(viewportFile);
if (viewport == null) {
    throw new IllegalStateException("Screenshot could not be decoded");
}

// Scroll first, then obtain geometry for the current viewport.
((JavascriptExecutor) driver).executeScript(
    "arguments[0].scrollIntoView({block:'center', inline:'nearest'});", card);
Rectangle r = card.getRect();

// These values are only valid if your measured setup maps CSS pixels to image pixels.
int x = r.getX();
int y = r.getY();
int width = r.getWidth();
int height = r.getHeight();
if (x < 0 || y < 0 || width <= 0 || height <= 0
        || x > viewport.getWidth() - width
        || y > viewport.getHeight() - height) {
    throw new IllegalArgumentException(
        "Element rectangle is outside screenshot: " + x + "," + y +
        " " + width + "x" + height + " in " +
        viewport.getWidth() + "x" + viewport.getHeight());
}
BufferedImage elementImage = viewport.getSubimage(x, y, width, height);
ImageIO.write(elementImage, "png", new File("element.png"));

The example deliberately fails with a useful message instead of allowing getSubimage to throw. In a real setup, verify that getRect() values are viewport-relative after scrolling and measure any device-scale conversion from the actual screenshot. Do not apply a universal multiplier such as two without checking the browser and display configuration.

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

When scrolling changes the result

  • Scroll the element into view before capturing.
  • Re-read its rectangle after scrolling; do not reuse a page-level location captured earlier.
  • Capture the viewport after the scroll, then validate against that image’s width and height.
  • Account for sticky headers or overlays if they cover the element.
  • If the element is larger than the viewport, decide whether you need a clipped viewport crop or a full element screenshot supported by the driver.

Diagnose the exact failure branch

The stack trace ends at getSubimage

Inspect the decoded image dimensions and every rectangle value. Log x, y, width, height, image.getWidth(), and image.getHeight(). Correct the coordinate origin, scroll and recalculate, or measure scaling. Do not merely increase the crop rectangle.

The stack trace is inside ImageIO or image construction

Confirm that the screenshot bytes decode to a non-null image and that the raster and color model are compatible with the operation you perform. Save the original bytes for inspection and test with a known-good PNG.

The stack trace is inside Selenium

Determine whether element screenshots are supported by that browser-driver combination. Record the complete exception text, Selenium version, browser and driver versions, Java version, operating system, and a minimal page and test. A title alone cannot identify a browser-specific defect or establish that upgrading will solve it.

The element screenshot call throws UnsupportedOperationException

Use the validated manual-crop path temporarily, or switch to a WebDriver implementation that supports element screenshots. Keep the bounds checks even in fallback code.

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

The image is unexpectedly empty or the page has not settled

Wait for the element’s required state before capture: visibility, dimensions, and any application-specific loading completion. A present DOM node can still have zero size or be covered by a transition.

Reliability checklist for test suites

  • Wait for the target element to be visible and have positive dimensions.
  • Capture the element directly whenever support is confirmed.
  • Use explicit waits rather than arbitrary sleeps for deterministic page state.
  • Save the browser, driver, Selenium, Java, OS, viewport, and scale settings with failed artifacts.
  • Keep temporary screenshot files only as long as needed, then copy or upload them.
  • Run a small reproducer before changing several dependencies at once.
  • Compare screenshot dimensions with CSS dimensions when diagnosing high-DPI or zoom issues.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If you only need a clean image or PDF of a URL, ScreenshotNeo provides a website screenshot API and MCP server. One GET request returns PNG, JPEG, WebP, or PDF. It accepts cookie and consent banners as a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers report the page verdict and billing status.

For a Java build or CI job, invoke the API with any HTTP client. The equivalent cURL call is:

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 API documentation for output and option details. The same request in Python is:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)

Node.js:

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`${res.status} ${await res.text()}`);
const fs = await import('node:fs/promises');
await fs.writeFile('shot.webp', Buffer.from(await res.arrayBuffer()));

ScreenshotNeo also offers element CSS selectors, full-page lazy-image loading, dark mode, device presets and custom viewports, retina scale, PDF paper and page-range controls, custom CSS and JavaScript, clicks, waits, request blocking, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, configurable caching, signed image links, asynchronous webhooks, bulk capture of up to 100 URLs per call, a usage API, OpenAPI, and an MCP server with take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients.

The Free plan includes 1,000 shots per month without a card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.

FAQ

Can I fix this by increasing the screenshot timeout?

Only if the underlying failure is a page-state or load problem. A timeout does not repair an invalid crop rectangle or coordinate mismatch.

Should I always use PNG?

PNG is convenient for lossless test artifacts, but the Selenium output type controls how data is returned; the browser or service may produce other formats when requested.

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

Does a full-page screenshot eliminate coordinate issues?

It can change the coordinate relationship, but it does not guarantee that DOM geometry and bitmap pixels share the same scale or origin. Validate dimensions in the actual decoded image.

Frequently Asked Questions

Can I fix this by increasing the screenshot timeout?

Only if the underlying failure is a page-state or load problem. A timeout does not repair an invalid crop rectangle or coordinate mismatch.

Should I always use PNG?

PNG is convenient for lossless test artifacts, but the Selenium output type controls how data is returned; the browser or service may produce other formats when requested.

Does a full-page screenshot eliminate coordinate issues?

It can change the coordinate relationship, but it does not guarantee that DOM geometry and bitmap pixels share the same scale or origin. Validate dimensions in the actual decoded image.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

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

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.