保存图片、Webview、安卓

3

我正在使用Android中的Webview来显示图片(主要使用Google Ajax API),现在如果我想将一张图片保存到本地存储,我该怎么做?我有图片的URL,可以用于保存。

2个回答

3
如果您有图像的URL,这很容易。您只需检索图像的字节即可。以下示例应该会对您有所帮助:
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;
}

这将返回一个字节数组,您可以将其存储在任何地方,或者通过以下方式重用它来创建图像:
Bitmap bm = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);

谢谢,我也是在类似的方向上工作,我成功地保存了一张图片,我使用了File对象来指定存储图像的路径。 - sat
干得好。当然,你可以从另一个来源加载图片。 - Sephy
我用更简单的方式实现了它:Bitmap image = BitmapFactory.decodeStream((InputStream) new URL("图片所在的Http地址").getContent()); - Emanuel Gianico

0

我知道这是一个相当古老的问题,但这个答案仍然有效:

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

当位图填满后,只需执行以下操作即可保存到存储器中(感谢https://dev59.com/v3RB5IYBdhLWcg3wXWG2#673014

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) {}
}

在我看来,这个答案比被接受的答案更加简洁和清晰。


缺点是您没有保存原始文件。 - Asiel Diaz Benitez

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接