ScreenshotNeo

BlogHow-to

How to Add a Base64 Image Thumbnail to a Selenium Extent Report

Embed Selenium screenshots directly in ExtentReports with Base64, including test-level attachments, failure logs, troubleshooting, and reusable Java helpers.

By the ScreenshotNeo team30 September 20269 min read

How to Add a Base64 Image Thumbnail to a Selenium Extent Report

Direct answer: capture the Selenium screenshot with OutputType.BASE64, then pass the returned string to ExtentReports. Use addScreenCaptureFromBase64String when attaching an image to a test, or create a media entity with MediaEntityBuilder.createScreenCaptureFromBase64String when attaching it to a log event.

String base64 = ((TakesScreenshot) driver)
    .getScreenshotAs(OutputType.BASE64);

ExtentTest test = extent.createTest("Checkout test");
test.pass("Checkout completed")
    .addScreenCaptureFromBase64String(base64, "Checkout thumbnail");

This keeps the screenshot in the report data instead of requiring a separate image file. Selenium documents OutputType.BASE64 as the way to obtain screenshot data in Base64, and ExtentReports exposes matching Base64 attachment methods in its Java API. See the Selenium OutputType API and the ExtentReports Java documentation.

1. What Base64 attachment means in ExtentReports

A WebDriver screenshot is returned as encoded image data. Selenium’s OutputType.BASE64 gives you that encoded payload as a Java String. ExtentReports accepts the same Base64 image string and creates a report attachment that its renderer can display as a thumbnail.

The two common attachment locations are different:

Use case ExtentReports API Typical message
Attach to the test entry addScreenCaptureFromBase64String “Checkout thumbnail”
Attach to a pass/fail log event MediaEntityBuilder.createScreenCaptureFromBase64String “Checkout failed”

The Base64 string is the image payload. Do not decode it and write it to disk unless you specifically need a separate file for another consumer. The cited ExtentReports examples pass the Base64 string directly to the API.

2. Complete Java example: attach a screenshot to a test

The following example uses Selenium’s Java API and ExtentReports’ Java API. It creates a WebDriver, captures a screenshot as Base64, attaches it to a test, flushes the report, and closes the browser.

The Selenium screenshot string flows directly into an ExtentReports attachment.
The Selenium screenshot string flows directly into an ExtentReports attachment.
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.reporter.ExtentSparkReporter;
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 Base64ExtentExample {
    public static void main(String[] args) {
        ExtentSparkReporter reporter =
            new ExtentSparkReporter("target/extent-report.html");
        ExtentReports extent = new ExtentReports();
        extent.attachReporter(reporter);

        WebDriver driver = new ChromeDriver();
        ExtentTest test = extent.createTest("Checkout test");

        try {
            driver.get("https://example.com");

            String base64 = ((TakesScreenshot) driver)
                .getScreenshotAs(OutputType.BASE64);

            test.pass("Page opened")
                .addScreenCaptureFromBase64String(
                    base64,
                    "Page screenshot"
                );
        } catch (Exception error) {
            test.fail("Checkout test failed: " + error.getMessage());
            throw error;
        } finally {
            driver.quit();
            extent.flush();
        }
    }
}

Replace the URL and test actions with your own flow. The important sequence is:

  1. Cast the driver to TakesScreenshot.
  2. Call getScreenshotAs(OutputType.BASE64).
  3. Pass the returned string to the ExtentReports attachment method.
  4. Call extent.flush() after logging so the report is written.

Adding an image title

The test-level API accepts an image title. A useful title identifies the state or step rather than repeating “screenshot.”

String base64 = ((TakesScreenshot) driver)
    .getScreenshotAs(OutputType.BASE64);

test.addScreenCaptureFromBase64String(
    base64,
    "Cart after applying discount"
);

3. Add the Base64 image to a pass or fail log

For a screenshot associated with one log event, create a media entity and pass it to fail, pass, or log. ExtentReports documents this pattern with MediaEntityBuilder.

import com.aventstack.extentreports.MediaEntityBuilder;
import com.aventstack.extentreports.MediaEntityModelProvider;
import com.aventstack.extentreports.Status;

String base64 = ((TakesScreenshot) driver)
    .getScreenshotAs(OutputType.BASE64);

MediaEntityModelProvider media = MediaEntityBuilder
    .createScreenCaptureFromBase64String(base64)
    .build();

test.fail("Checkout failed", media);

// Equivalent form:
test.log(Status.FAIL, "Checkout failed", media);

This form keeps the message and image together in the event where the failure is recorded. It is useful when a test has several checkpoints and each failure needs its own visual state.

A reusable failure helper

Put screenshot capture in a helper so every test uses the same naming and error handling policy.

import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.MediaEntityBuilder;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;

public final class ExtentScreenshot {
    private ExtentScreenshot() {}

    public static void attach(
            WebDriver driver,
            ExtentTest test,
            String message) {
        String base64 = ((TakesScreenshot) driver)
            .getScreenshotAs(OutputType.BASE64);

        test.fail(
            message,
            MediaEntityBuilder
                .createScreenCaptureFromBase64String(base64)
                .build()
        );
    }
}

Call it from a catch block:

try {
    // test steps
} catch (Exception error) {
    ExtentScreenshot.attach(driver, test, "Failure state");
    throw error;
}

The documented Java signatures can throw IOException, depending on the ExtentReports version and method you use. If your compiler reports that exception, either declare it on the surrounding method or catch it in the helper.

4. Base64 data format and data URI prefixes

Keep the string returned by Selenium intact when passing it to ExtentReports. The cited Java examples accept the Base64 image string directly. Do not prepend data:image/png;base64, unless a different renderer explicitly requires a data URI.

Adding a prefix in the wrong place can make the attachment invalid because the ExtentReports method expects the encoded image payload. If you must pass the image to another HTML component, add the renderer-specific prefix at that boundary and leave the value used by ExtentReports unchanged.

5. Test-level versus log-level screenshots

Choose the attachment point based on how readers navigate the report:

Choose a test-level attachment for summaries or a media entity for a specific log event.
Choose a test-level attachment for summaries or a media entity for a specific log event.
  • Test-level: use addScreenCaptureFromBase64String for a summary image such as the final checkout state or a successful page load.
  • Log-level: use MediaEntityBuilder when the image explains a specific failure, assertion, or checkpoint.
  • Both: attach a final summary at test level and failure evidence to the exact failed log. Avoid attaching the same large image repeatedly unless it helps navigation.

ExtentReports also documents path-based screenshot methods. A file path can be preferable when another system consumes image files, while Base64 keeps the attachment embedded in the report data. The official guide does not publish a universal size or rendering benchmark, so choose based on report portability, report size, renderer compatibility, and file retention requirements.

6. Capture timing and useful Selenium options

A screenshot records the browser state at the instant getScreenshotAs runs. Capture after the condition you want to show has been established:

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement confirmation = wait.until(
    ExpectedConditions.visibilityOfElementLocated(
        By.id("confirmation")
    )
);

String base64 = ((TakesScreenshot) driver)
    .getScreenshotAs(OutputType.BASE64);

test.pass("Confirmation visible")
    .addScreenCaptureFromBase64String(
        base64,
        "Confirmation: " + confirmation.getText()
    );

For a failure screenshot, capture before cleanup changes the page. If your teardown dismisses dialogs, navigates away, or quits the driver first, the resulting image may show the wrong state or fail completely.

Use an explicit wait for a known element instead of a fixed sleep when possible. A fixed delay can capture too early on a slow run and wastes time on a fast run. If the page contains animations, wait for the animation’s completion condition or capture after the relevant element becomes stable.

7. Troubleshooting common errors

Symptom Likely cause Fix
ClassCastException when casting to TakesScreenshot The driver implementation does not support screenshots. Use a WebDriver implementation that implements TakesScreenshot, then cast the active driver instance.
Thumbnail is missing but the test is present The report was not flushed, or the attachment call was skipped by an earlier exception. Call extent.flush() after logging, normally in a finally block, and inspect the first exception.
Image shows the previous page Capture ran before navigation or an asynchronous update completed. Wait for a URL, element, or state that proves the new page is ready, then capture.
Image appears broken The Base64 value was modified, truncated, or given an unsupported prefix. Pass Selenium’s returned string unchanged to ExtentReports. Add a data URI prefix only for a renderer that requires it.
IOException compilation error Your ExtentReports method signature declares a checked exception. Declare or catch IOException in the helper or test method, according to your dependency version.
Screenshot is blank The browser is between navigations, the page failed to load, or a modal/overlay hides the content. Wait for a meaningful element, verify the URL and page state, and capture before teardown.
Parallel tests show confusing attachments Shared test or driver objects are being used across threads. Keep each WebDriver and ExtentTest associated with one test execution. Do not overwrite a shared Base64 variable.
Report becomes difficult to open Many high-resolution Base64 images increase report data. Capture at deliberate checkpoints, avoid duplicate attachments, and use file-based storage when your retention workflow needs separate assets.

8. Performance, reliability, and report-size considerations

Base64 adds the encoded image payload to the report data. The practical cost depends on screenshot dimensions, image format selected by the browser driver, and how many screenshots you attach. The authoritative ExtentReports material does not provide a general rendering-time or size benchmark, so measure your own suite if report size affects CI artifacts.

  • Capture only when the image answers a debugging question.
  • Use one failure image per failed checkpoint instead of taking screenshots after every command.
  • Flush once at the end of a test run unless your runner needs incremental report output.
  • Keep capture and logging close together so the image corresponds to the message.
  • Preserve the original exception after attaching evidence; a reporting failure should not hide the test failure.

For reliability, place the attachment in a protected reporting path. If screenshot capture itself fails, log that failure separately and retain the original test error. In CI, ensure the generated report directory is published as an artifact after the test process exits.

9. Complete JUnit-style failure pattern

@AfterEach
void recordFailure(TestInfo info) {
    if (driver == null) {
        return;
    }

    try {
        String base64 = ((TakesScreenshot) driver)
            .getScreenshotAs(OutputType.BASE64);

        test.fail(
            "Failure in " + info.getDisplayName(),
            MediaEntityBuilder
                .createScreenCaptureFromBase64String(base64)
                .build()
        );
    } catch (Exception captureError) {
        test.warning("Could not capture failure screenshot: "
            + captureError.getMessage());
    }
}

Adapt the lifecycle hook to your test framework. The key reliability rule is to capture while the driver is still alive and to keep screenshot errors from replacing the original assertion or exception.

10. Or skip the browser setup

If you need a screenshot image for a report but do not want to maintain browser-driver setup, ScreenshotNeo provides a website screenshot API. One GET request returns PNG, JPEG, WebP, or PDF output, and its API can be used from CI or a reporting service.

See the ScreenshotNeo documentation for request options. This is a complete request using the required API format:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
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)
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(`Screenshot failed: ${res.status}`);
const bytes = await res.arrayBuffer();

ScreenshotNeo removes cookie and consent banners, newsletter popups, and chat widgets before the capture. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and the response identifies the result with X-Page-Verdict and X-Billed headers. Its MCP server lets Claude, Cursor, and other MCP clients call take_screenshot, get_page_info, and capture_pdf. You can also set custom CSS and JavaScript, wait conditions, device and viewport settings, cookies, headers, geolocation, caching, and other capture options.

The Free plan includes 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 screenshots. Create a free ScreenshotNeo account.

11. FAQ

Can I attach Base64 without saving a PNG?

Yes. Selenium returns the encoded screenshot string, and ExtentReports accepts that string directly through its Base64 methods.

Should I use a data URI?

Not for the ExtentReports methods shown here. Pass the Base64 string unchanged. Add a data URI prefix only when another renderer specifically documents that format.

Which method should I use for a failed assertion?

Use MediaEntityBuilder.createScreenCaptureFromBase64String and pass the resulting media entity to test.fail or test.log(Status.FAIL, ...).

Why does the API differ between examples online?

ExtentReports method signatures vary between major versions and language bindings. Confirm the dependency version before copying an example, and check whether your method declares IOException.

Can the same Base64 string be attached more than once?

Yes, but duplicate high-resolution attachments increase report data. Reuse it only when the repeated placement helps readers find the evidence.