3

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.

sat
  • 40,138
  • 28
  • 93
  • 102

2 Answers2

3

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
  • 50,022
  • 30
  • 123
  • 131
  • 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 Aug 21 '10 at 10:56
  • well done. indeed you can load the image from another source of course. – Sephy Aug 21 '10 at 11:02
  • I made it in a much more simple way: Bitmap image = BitmapFactory.decodeStream((InputStream) new URL("Http Where your Image is").getContent()); – Emanuel Gianico Apr 04 '14 at 03:22
0

I know this is a quite old but this is valid too:

Bitmap image = BitmapFactory.decodeStream((InputStream) new URL("Http Where your Image is").getContent());

With the Bitmap filled up, just do this to save to storage (Thanks to https://stackoverflow.com/a/673014/1524183)

FileOutputStream out;
try {
       out = new FileOutputStream(filename);
       image.compress(Bitmap.CompressFormat.PNG, 90, out);
} catch (Exception e) {
    e.printStackTrace();
} finally {
       try{
           out.close();
       } catch(Throwable ignore) {}
}

IHMO much more cleaner and simpler than the accepted answer.

Community
  • 1
  • 1
Emanuel Gianico
  • 330
  • 6
  • 19