Java Selenium - cannot download image from Chrome browser and save as .png file

24 views Asked by At

I want to download image from Chrome web browser and save it as .png file. The following code creates a file in Download directory, but the size of the file is only 417 bytes and when I want to open the file in Paint or any other program I get error "This is not a valid bitmap file or its format is not currently supported."

It turns out that src returns url address to the whole http page, not to directly to the image. Is thare a way to get round this problem ?

I addded the following code and it returns whole html page, not the image directly

String contentType = connection.getContentType();
    System.out.println("Content Type: " + contentType); 

contentType returns "text/html"; charset=ISO-8859-1

WebElement image = webDriver.findElement(By.xpath("//img"));
String imageUrl = image.getAttribute("src");

String directory = System.getProperty("user.dir") + File.separator + "Downloads" + File.separator;

try {
    
        URL url = new URL(imageURL);
        URLConnection connection = url.openConnection();

        InputStream inputStream = connection.getInputStream();
        OutputStream outputStream = new FileOutputStream(directory+"downloadedImage.png");

        byte[] buffer = new byte[2048];
        int length;
        while ((length = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, length);
        }

        inputStream.close();
        outputStream.close();

        System.out.println("Image downloaded successfully!");
    } catch (IOException e) {
        e.printStackTrace();
    }
}
0

There are 0 answers