吴小龙同學

Android保存图片并显示系统图库

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/**
* 0 保存失败;
* 1 保存成功;
* 2 已经存在
*/
class SaveImageToGalleryTask extends AsyncTask<Objects, Objects, Integer> {
@Override
protected Integer doInBackground(Objects... params) {
Bitmap bitmap = null;
try {
bitmap = Picasso.with(GirlImageDetailActivity.this).load("图片URL").get();
} catch (IOException e) {
e.printStackTrace();
}
if (bitmap == null) {
return 0;
}
File appDir = new File(Environment.getExternalStorageDirectory(), "hua");
if (!appDir.exists()) {
appDir.mkdir();
}
final String fileName = "图片名字"+ ".png";
File file = new File(appDir, fileName);
if (file.exists()) {
return 2;
} else {
try {
FileOutputStream fileOutputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
// 其次把文件插入到系统图库
MediaStore.Images.Media.insertImage(GirlImageDetailActivity.this.getContentResolver(), file.getAbsolutePath(), fileName, null);
// 最后通知图库更新
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getAbsolutePath()));
sendBroadcast(intent);
return 1;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
}
@Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
switch (integer) {
case 0:
Snackbar.make(detailLayout, "保存失败", Snackbar.LENGTH_SHORT).show();
break;
case 1:
File appDir = new File(Environment.getExternalStorageDirectory(), "hua");
Snackbar.make(detailLayout, "成功保存至" + appDir.getAbsolutePath(), Snackbar.LENGTH_SHORT).show();
break;
case 2:
Snackbar.make(detailLayout, "图片已经存在", Snackbar.LENGTH_SHORT).show();
break;
}
}
}


联系我

我的微信公众号:吴小龙同学,欢迎关注交流~

赞助商:躲角落的猫咪