保存图像,webview,android

时间:2010-08-13 06:33:45

标签: android webview

我在android中使用webview来显示图像(主要使用google ajax API),现在如果我想将图像保存到本地存储中,我该怎么办?我有图像网址,可用于保存。

2 个答案:

答案 0 :(得分:3)

如果你有图片网址,这很容易。您只需要检索图像的字节。以下是一个可以帮助您的示例:

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

这将返回一个byteArray,您可以将其存储在任意位置,或者重新创建图像,通过这样做:

Bitmap bm = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);

答案 1 :(得分:0)

我知道这是一个相当古老但这也是有效的:

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

填充Bitmap后,只需执行此操作即可保存到存储空间(感谢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比接受的答案更清洁,更简单。