/**
* 保存图片到相册(适配安卓11)
*/
@SuppressLint("SimpleDateFormat")
public static void saveImageToGallery2(Context context, Bitmap image) {
long mImageTime = System.currentTimeMillis();
String imageDate = new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date(mImageTime));
String SCREENSHOT_FILE_NAME_TEMPLATE = "plvlive_%s.png";//图片名称,以"plvlive_"+时间戳命名
String mImageFileName = String.format(SCREENSHOT_FILE_NAME_TEMPLATE, imageDate);
final ContentValues values = new ContentValues();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
//Environment.DIRECTORY_SCREENSHOTS:截图,图库中显示的文件夹名。"dh"
values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES + File.separator + "plvlive");
}
values.put(MediaStore.MediaColumns.DISPLAY_NAME, mImageFileName);
values.put(MediaStore.MediaColumns.MIME_TYPE, "image/png");
values.put(MediaStore.MediaColumns.DATE_ADDED, mImageTime / 1000);
values.put(MediaStore.MediaColumns.DATE_MODIFIED, mImageTime / 1000);
ContentResolver resolver = context.getContentResolver();
final Uri uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
OutputStream out = null;
try {
out = resolver.openOutputStream(uri);
image.compress(Bitmap.CompressFormat.PNG, 100, out);
Toast.makeText(context, "截图已保存至相册~", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
resolver.delete(uri, null);
}
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Android保存图片到相册(适配安卓11)
于 2022-09-24 12:55:08 首次发布