Download an image directly with Selenium in Java

In this quick tutorial, we will explain how to download an image directly with Selenium in Java. The advantage of this method, instead of using a classic HTTP client like CURL, is that the website will behave exactly the same way as if you were browsing it with a classic browser like Chrome.

1) Setup the Selenium driver and the image URL variables

Replace these 2 variables with your own values:

String seleniumDriver = "/path/to/your/selenium/driver";
String imageUrl = "";

For this tutorial, we will download an image from our website, but the tutorial will work with any other image.

2) Open the image in Selenium

To open the image in Selenium, simply do:

System.setProperty("", seleniumDriver);
ChromeDriver driver = new ChromeDriver();

3) Execute a Javascript script that downloads the image as Base64

Run the following Java code:

String script = "var c = document.createElement('canvas');\n" +
                "var ctx = c.getContext('2d');\n" +
                "var img = document.getElementsByTagName('img')[0];\n" +
                "c.height = img.naturalHeight;\n" +
                "c.width = img.naturalWidth;\n" +
                "ctx.drawImage(img, 0, 0,img.naturalWidth, img.naturalHeight);\n" +
                "var base64Url = c.toDataURL();\n" +
                "return base64Url;";

String base64Url = driver.executeScript(script).toString();

The Java variable base64Url contains the image as Base64.

4) Parse the base64Url

To parse the base64Url, extract the image and its extension, run:

String pattern = "^data:image/(.*?);base64,(.*?)$";
Matcher matcher = Pattern.compile(pattern).matcher(base64Url);

String extension =;
String base64 =;

5) Save the image as a file in the ~/Downloads folder

String downloadPath = System.getProperty("user.home") + File.separator + "Downloads" + File.separator + "image." + extension;
FileUtils.writeByteArrayToFile(new File(downloadPath), data);

System.out.println("Downloaded image to: " + downloadPath);

In the console, you will obtain the following:

Downloaded image to: /home/neo/Downloads/image.png

That’s it for this tutorial ! Thank you for reading, and if you have any question, please leave a reply below. We answer within 24h.

Leave a Reply

Your email address will not be published. Required fields are marked *