开发者

Saving image, webview, android

开发者 https://www.devze.com 2023-01-11 15:30 出处:网络
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, whic开发者_运维知识库h can be used fo

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, whic开发者_运维知识库h can be used for saving.


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);


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消