0

I'm creating code to download some images from the web using HtmlUnit. But when I save the image with HtmlUnit the quality of the image is very low compared with the original image. I used this code to save the img url to a file.

 try {
              HtmlImage imgX = (HtmlImage) 
              page.getByXPath("//img").get(0);
              Thread.sleep(3000);

              File imageFile = new File(dir +"/"+ name);
              imgX.saveAs(imageFile);
              System.out.println("Done!!!!");
 } catch (Exception e) {
              e.printStackTrace();
 }

Are there other options to get the image with the best quality?

I tried using this: How to convert an <img... in html to byte [] in Java But the image was not created.

Community
  • 1
  • 1

1 Answers1

0

Get the WebResponse from HtmlImage:

InputStream inputStream = imgX.getWebResponse(true).getContentAsStream();

And then work directly on InputStream:

File imageFile = new File(dir +"/"+ Name);
FileOutputStream outputStream = new FileOutputStream(imageFile);
IOUtils.copy(inputStream, outputStream);
brnfd
  • 464
  • 2
  • 8