andriod开发app怎么保存ImageView的图片报错如下

具体写法如下:


下午好🌅🌅🌅
本答案参考通义千问
根据你的描述,你在尝试将 ImageView 中的图片保存到图库时遇到了 ClassCastException 异常。这个异常通常发生在你试图将一个类型为 GlideBitmapDrawable 的对象强制转换为 BitmapDrawable。
正确获取 ImageView 中的图片
GlideBitmapDrawable,而不是 BitmapDrawable。GlideBitmapDrawable 转换为 Bitmap。修改 saveImageToGallery 方法
Glide 提供的方法来获取 Bitmap。以下是修改后的代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView PICIMG = findViewById(R.id.pic_details);
requestStoragePermission();
PICIMG.setOnLongClickListener(v -> {
System.out.println("1111111111111111111111111111111111111111");
saveImageToGallery(PICIMG);
System.out.println("1111111111111111111111111111111111111111");
return true;
});
}
private void requestStoragePermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
STORAGE_PERMISSION_CODE);
}
}
private void saveImageToGallery(ImageView imageView) {
try {
// 获取ImageView中的图片并转换为Bitmap
Drawable drawable = imageView.getDrawable();
Bitmap bitmap;
if (drawable instanceof GlideBitmapDrawable) {
GlideBitmapDrawable glideBitmapDrawable = (GlideBitmapDrawable) drawable;
bitmap = glideBitmapDrawable.getBitmap();
} else if (drawable instanceof BitmapDrawable) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
bitmap = bitmapDrawable.getBitmap();
} else {
throw new IllegalStateException("Unsupported drawable type");
}
// 将Bitmap保存到图库
MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "Image_" + System.currentTimeMillis(), "Image saved from the app");
Toast.makeText(this, "Image saved to gallery!", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "Failed to save image!", Toast.LENGTH_SHORT).show();
}
}
检查 Drawable 类型:
imageView.getDrawable() 返回的是 Drawable 对象。Drawable 是否为 GlideBitmapDrawable 或 BitmapDrawable。获取 Bitmap:
GlideBitmapDrawable,使用 glideBitmapDrawable.getBitmap() 获取 Bitmap。BitmapDrawable,直接使用 bitmapDrawable.getBitmap() 获取 Bitmap。处理异常:
try-catch 块来捕获可能的异常,并显示相应的提示信息。通过上述步骤,你应该能够解决 ClassCastException 并成功将 ImageView 中的图片保存到图库中。