我正在使用Android中的Webview来显示图片(主要使用Google Ajax API),现在如果我想将一张图片保存到本地存储,我该怎么做?我有图片的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);
我知道这是一个相当古老的问题,但这个答案仍然有效:
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) {}
}
在我看来,这个答案比被接受的答案更加简洁和清晰。