在 Asynctask 中下载 Bitmap 图像并将其存储在磁盘上,可以使用以下代码示例:
class DownloadImageTask extends AsyncTask {
private String filePath;
public DownloadImageTask(String filePath) {
this.filePath = filePath;
}
protected Bitmap doInBackground(String... urls) {
String imageUrl = urls[0];
Bitmap bitmap = null;
try {
InputStream in = new java.net.URL(imageUrl).openStream();
bitmap = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap result) {
if (result != null) {
try {
File file = new File(filePath);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
FileOutputStream out = new FileOutputStream(file);
result.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
}
}
在调用 AsyncTask 时,传递一个文件路径作为参数,例如:
new DownloadImageTask("/sdcard/myimage.png").execute("http://example.com/image.png");
这将从 http://example.com/image.png 下载图像并将其保存在 /sdcard/myimage.png 中。请确保在 AndroidManifest.xml 中声明相应的权限。