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

随声附和 提交于 2019-12-02 13:51:50

问题


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.


回答1:


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.




回答2:


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;

}



来源:https://stackoverflow.com/questions/2138961/how-to-convert-an-img-in-html-to-byte-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!