Android 使用ActivityResultLauncher点击button保存imageview图片
获取权限
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES"/>
button实现
private ActivityResultLauncher<String> saveImageLauncher;
private Bitmap imageBitmap;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
imageView = view.findViewById(R.id.image_home);
Button saveImageButton = view.findViewById(R.id.btn_home_save);
saveImageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
requestSaveImageStoragePermission();
}
}
});
权限检查
@RequiresApi(api = Build.VERSION_CODES.TIRAMISU)
private void requestSaveImageStoragePermission() {
if (ActivityCompat.checkSelfPermission(requireContext(), Manifest.permission.READ_MEDIA_IMAGES) != PackageManager.PERMISSION_GRANTED) {
saveImageLauncher.launch(Manifest.permission.READ_MEDIA_IMAGES);
} else {
saveImageToGallery();
}
}
ActivityResultLauncher启动保存图片
// 保存图片
saveImageLauncher = registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> {
if (isGranted) {
saveImageToGallery();
} else {
Toast.makeText(getActivity(), "Permission denied", Toast.LENGTH_SHORT).show();
}
});
保存图片实现
private void saveImageToGallery() {
// 假设你已经有了Bitmap对象,这里命名为imageBitmap
// 获取ImageView中的Bitmap
Bitmap imageBitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
// 根据实际情况获取Bitmap
ContentResolver resolver = requireContext().getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, "Image.jpg");
contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES);
}
Uri imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
try {
if (imageUri != null) {
OutputStream outputStream = resolver.openOutputStream(imageUri);
if (outputStream != null) {
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.close();
}
// 通知图库更新
requireActivity().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, imageUri));
Toast.makeText(getActivity(), "Image saved to gallery", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getActivity(), "Failed to save image", Toast.LENGTH_SHORT).show();
}
}
如果是要保存网络图片或是其他路径图片,需要替换这个imageBitmap
Bitmap imageBitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();