Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving image, webview, android

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.

like image 759
sat Avatar asked Aug 16 '26 14:08

sat


1 Answers

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);
like image 129
Sephy Avatar answered Aug 18 '26 04:08

Sephy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!