Thursday, June 28, 2012

download image from web page in java


Image image = null;
try 
    URL url = new URL(imageURL);
    image = ImageIO.read(url);
} catch (IOException e) {
}


Get the image binary data using InputStream and write to local disk
 URL url = new URL(imageURL);
InputStream in = new BufferedInputStream(url.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[8192];
int n = 0;
while (-1!=(n=in.read(buf)))
{
   out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
At last write the image to local filesystem
FileOutputStream fos = new FileOutputStream(/home/Pictures/out.png);
    fos.write(response);
    fos.close();

No comments:

Post a Comment