Categories
Java

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 = "https://eazytutorial.com/wp-content/uploads/2021/08/26_0.png";

For this tutorial, we will download an image from our website eazytutorial.com, 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("webdriver.chrome.driver", seleniumDriver);
ChromeDriver driver = new ChromeDriver();
driver.get(imageUrl);

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);
matcher.find();

String extension = matcher.group(1);
String base64 = matcher.group(2);

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 *