- 低版本还是老方法,在DCIM文件夹下保存File,然后发个广播通知相册刷新
- 新版本要用Media Store Api,本质上还是OutputStream写。
- 而且高版本不需要write权限,10以下还是需要write权限的。
public static void addImageToGallery(final Context context,
final Bitmap src,
final Bitmap.CompressFormat format,
final int quality,
final boolean recycle) {
String suffix = Bitmap.CompressFormat.JPEG.equals(format) ? "JPG" : format.name();
String fileName = System.currentTimeMillis() + "_" + quality + "." + suffix;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
File picDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
File destFile = new File(picDir, context.getPackageName() + "/" + fileName);
if (!save(src, destFile, format, quality, recycle)) {
return;
}
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.parse("file://" + destFile.getAbsolutePath()));
context.sendBroadcast(intent);
} else {
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, fileName);
contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/*");
Uri contentUri;
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else {
contentUri = MediaStore.Images.Media.INTERNAL_CONTENT_URI;
}
contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_DCIM + "/" + context.getPackageName());
contentValues.put(MediaStore.MediaColumns.IS_PENDING, 1);
Uri uri = context.getContentResolver().insert(contentUri, contentValues);
if (uri == null) {
return;
}
OutputStream os = null;
try {
os = context.getContentResolver().openOutputStream(uri);
src.compress(format, quality, os);
contentValues.clear();
contentValues.put(MediaStore.MediaColumns.IS_PENDING, 0);
context.getContentResolver().update(uri, contentValues, null, null);
} catch (Exception e) {
context.getContentResolver().delete(uri, null, null);
e.printStackTrace();
} finally {
try {
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static boolean save(final Bitmap src,
final File file,
final Bitmap.CompressFormat format,
final int quality,
final boolean recycle) {
OutputStream os = null;
boolean ret = false;
try {
os = new BufferedOutputStream(new FileOutputStream(file));
ret = src.compress(format, quality, os);
if (recycle && !src.isRecycled()) {
src.recycle();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return ret;
}