保存图片到本地分三步:
- 保存图片到本地指定文件夹
- 将图片加入图库
- 通知图库扫描更新
保存图片到本地指定文件夹
File bitmapCacheDir = new File(SDCardUtil.getSDCardPath() + "bitmapCache");
if (!bitmapCacheDir.exists()) {
bitmapCacheDir.mkdir();
}
String fileName = System.currentTimeMillis() + ".jpg";
File file = new File(bitmapCacheDir, fileName);
FileOutputStream fileOutputStream = null;
try {
file.createNewFile();
fileOutputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
将图片加入图库
try {
MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, null);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
通知图库扫描更新
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));