通过检查写入文件的权限,确保已获得适当的权限后再保存图像;如果没有权限,则通知用户请求必要的权限。示例:
//确保有适当的权限 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { //获得写入权限,然后保存图像 saveImage(bitmap); } else { //如果没有权限,则请求必要的权限 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_WRITE_EXTERNAL_STORAGE_PERMISSION); }
//在回调中处理权限请求的结果 @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { if (requestCode == REQUEST_CODE_WRITE_EXTERNAL_STORAGE_PERMISSION) { if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { //获得写入权限,然后保存图像 saveImage(bitmap); } else { //如果没有权限,则做出通知或者其他处理 } } }
//实际的保存图像方法 private void saveImage(final Bitmap bitmap) { final String imageName = "my_image.jpg"; final File storageDir = Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES); final File imageFile = new File(storageDir, imageName);
OutputStream out = null;
try {
out = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
Toast.makeText(this, "Image saved to gallery", Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
上一篇:AndroidImageReader-指定格式无效42
下一篇:AndroidImageView-当adjustViewBounds为true时,minWidth/minHeight无效的问题