views:

63

answers:

1

Hi, I am using webview in android to display images (mainly using google ajax API), Now if I want to save an image into local storage, How do I do ? I have image url, which can be used for saving.

A: 

If you have the image url, this is dead easy. You just have to retrieve the bytes of the image. Here is a sample that should help you :

try {
  URL url = new URL(yourImageUrl);
  InputStream is = (InputStream) url.getContent();
  byte[] buffer = new byte[8192];
  int bytesRead;
  ByteArrayOutputStream output = new ByteArrayOutputStream();
  while ((bytesRead = is.read(buffer)) != -1) {
    output.write(buffer, 0, bytesRead);
  }
  return output.toByteArray();
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}

This will return a byteArray that you can either store wherever you like, or reuse to create an image, by doing that :

Bitmap bm = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
Sephy
Thanks , I worked on similar line and I was able to save an image, I used File object to specify the path as to where to store the image.
sat
well done. indeed you can load the image from another source of course.
Sephy