分情况获取权限
JPEGData jpegData = hatomPlayer.screenshot();
if (jpegData != null){
if(Build.VERSION.SDK_INT > 29){
saveBitmap29(this,byteArrToBitmap(jpegData.mJpegBuffer));
}else {
//请求WRITE_EXTERNAL_STORAGE权限
int hasWriteContactsPermission1 = checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (hasWriteContactsPermission1 != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_CODE_ASK_PERMISSIONS);
}else {
BitmapUtils.saveBitmapBefore10(this,byteArrToBitmap(jpegData.mJpegBuffer));
}
}
}
api>29:
/**
* android10之后
* 大于29
* @param context
* @param bitmap
*/
public static void saveBitmap29(Context context,Bitmap bitmap) {
try {
//获取要保存的图片的位图
//创建一个保存的Uri
ContentValues values = new ContentValues();
//设置图片名称
values.put(MediaStore.Images.Media.DISPLAY_NAME, System.currentTimeMillis() + "_fas.png");
//设置图片格式
values.put(MediaStore.Images.Media.MIME_TYPE, "image/png");
//设置图片路径
values.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES);
Uri saveUri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
if (TextUtils.isEmpty(saveUri.toString())) {
Toast.makeText(context, "保存失败!", Toast.LENGTH_SHORT).show();
return;
}
OutputStream outputStream = context.getContentResolver().openOutputStream(saveUri);
//将位图写出到指定的位置
//第一个参数:格式JPEG 是可以压缩的一个格式 PNG 是一个无损的格式
//第二个参数:保留原图像90%的品质,压缩10% 这里压缩的是存储大小
//第三个参数:具体的输出流
if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream)) {
Toast.makeText(context, "保存成功!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "保存失败!", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
如果小于29
/**
* android10之前
* @param context
* @param bmp
*/
public static void saveBitmapBefore10(Context context,Bitmap bmp) {
String file_path = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/TEST";
String file_name = System.currentTimeMillis() + "_test.png";
File file = null;
try {
File dir = new File(file_path);
if (!dir.exists())
dir.mkdirs();
file = new File(dir, file_name);
FileOutputStream fOut = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
Log.e("error in saving image", e.getMessage());
}
try {
MediaStore.Images.Media.insertImage(context.getContentResolver(),
file.getAbsolutePath(), file_name, null);
Toast.makeText( context,"保存成功!", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
Toast.makeText( context, "保存失败!", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
// // 最后通知图库更新
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
Uri.fromFile(new File(file.getPath()))));
}