Amit
Amit

Reputation: 34745

How to convert an <img... in html to byte [] in Java

I have opened a webpage in HtmlUnit headless browser. Now that webpage contains a image html tag as follows:

<img src="..." />

So I want that image only. But the problem is that the same src URL of the image shows diff. image each time. Means, if we refresh the img src URL, then it shows diff. image each time.

So how to get the image that is displayed on the html page.

Upvotes: 1

Views: 2661

Answers (2)

Sujith
Sujith

Reputation: 1399

This is the function to store your image with fully qualified I

   protected String saveImage(String imageUrl) throws Exception {

   InputStream inputStream;
   OutputStream os;
   ByteArrayOutputStream byteArrayOutputStream;
   String destinationFile = "File path where you want ot store the image";
   URL url = new URL(imageUrl);
   inputStream = url.openStream();
   byteArrayOutputStream = new ByteArrayOutputStream();
   os = new FileOutputStream(destinationFile);
   int read;
   String barcode = null;
   while ((read = inputStream.read()) != -1) {
       os.write(read);
       byteArrayOutputStream.write(read);
       barcode = byteArrayOutputStream.toString();
   }
   inputStream.close();
   os.close();
   byteArrayOutputStream.close();



   return barcode;

}

Upvotes: 0

Valentin Rocher
Valentin Rocher

Reputation: 11669

When you get the HTMLPage, you have to get the image through one of its method. You can then get an HtmlImage, which can be saved as a file. You'll just have to analyse this file later.

Upvotes: 1

Related Questions