/**
* 保存图片到相册
*/
public static boolean saveImgToPics(Context context, String path) {
try {
ContentResolver mResolver = context.getContentResolver();
String insertImage = MediaStore.Images.Media.insertImage(mResolver, path, "name", "description");
//需进行此转换操作,否则保存的图片时间为1970年的,会出现在相册的最上面
String absPath = getRealPathFromUri(Uri.parse(insertImage), context);
if (TextUtils.isEmpty(absPath)) {
CrashReport.postCatchedException(new Exception("保存图片到相册失败,absPath=" + absPath));
return false;
}
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(absPath))));
return true;
} catch (Exception e) {
CrashReport.postCatchedException(e);
return false;
}
}
/**
* 得到绝对地址
*/
private static String getRealPathFromUri(Uri contentUri, Context context) {
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
try {
int columnIndex = 0;
if (cursor != null) {
columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(columnIndex);
} else {
return "";
}
} catch (Exception e) {
CrashReport.postCatchedException(e);
return "";
} finally {
if (cursor != null) {
cursor.close();
}
}
}
image.png