Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to download image from any web page in java

hi I am trying to download image from web page. I am trying to download the image from 'http://www.yahoo.com' home page. Please tell me how to pass 'http://www.yahoo.com' as a input. And on opening this web page how to fetch image from this page. Please give me java code to fetch the image from web page.

like image 844
DJ31 Avatar asked May 04 '11 10:05

DJ31


People also ask

How do I save an image as a URL?

Right-click on the image and select Properties. Find and highlight the URL address to select it. Right-click and select Copy or press Ctrl + C to copy the image. Paste the address into a new email, text editor, or new browser window.


1 Answers

try (URL url = new URL("http://www.yahoo.com/image_to_read.jpg")) {     Image image = ImageIO.read(url); } catch (IOException e) {     // handle IOException } 

See javax.imageio package for more info. That's using the AWT image. Otherwise you could do:

URL url = new URL("http://www.yahoo.com/image_to_read.jpg"); InputStream in = new BufferedInputStream(url.openStream()); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int n = 0; while (-1!=(n=in.read(buf))) {    out.write(buf, 0, n); } out.close(); in.close(); byte[] response = out.toByteArray(); 

And you may then want to save the image so do:

FileOutputStream fos = new FileOutputStream("C://borrowed_image.jpg"); fos.write(response); fos.close(); 
like image 93
planetjones Avatar answered Oct 14 '22 08:10

planetjones