Java Android:获取图像的URI时出错
在我的Android应用程序中,有一个图像视图。我需要获取此图像并将其保存在sqlite数据库中。我尝试获取图像的uri并将其保存在数据库中。我使用了下面的代码段来获取图像的uriJava Android:获取图像的URI时出错,java,android,sqlite,bitmap,Java,Android,Sqlite,Bitmap,在我的Android应用程序中,有一个图像视图。我需要获取此图像并将其保存在sqlite数据库中。我尝试获取图像的uri并将其保存在数据库中。我使用了下面的代码段来获取图像的uri // get byte array from image view Drawable d = image.getBackground(); BitmapDrawable bitDw = ((BitmapDrawable) d); Bitmap bitmap = bitD
// get byte array from image view
Drawable d = image.getBackground();
BitmapDrawable bitDw = ((BitmapDrawable) d);
Bitmap bitmap = bitDw.getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] imageInByte = stream.toByteArray();
//get URI from byte array
String path = null;
try {
path = Images.Media.insertImage(getContentResolver(), imageInByte.toString(),
"title", null);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Uri imageUri = Uri.parse(path);
String uriString = imageUri.toString() ;
System.out.println(uriString);
ContentValues values = new ContentValues();
values.put(COLUMN_PROFILE_PICTURE, uriString);
但是日志猫说
11-12 06:54:21.028: E/AndroidRuntime(863): FATAL EXCEPTION: main
11-12 06:54:21.028: E/AndroidRuntime(863): java.lang.ClassCastException: android.graphics.drawable.GradientDrawable cannot be cast to android.graphics.drawable.BitmapDrawable
错误被指向这一行
BitmapDrawable bitDw = ((BitmapDrawable) d);
问题在ClassCastException中说明,您不能将GradientDrawable强制转换为位图Drawable 以下是解决方法:
...
Drawable d = image.getBackground();
GradientDrawable bitDw = ((GradientDrawable) d); // the correct cast
// create a temporary Bitmap and let the GradientDrawable draw on it instead
Bitmap bitmap = Bitmap.createBitmap(image.getWidth(),
image.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
bitDw.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
bitDw.draw(canvas);
// Bitmap bitmap = bitDw.getBitmap(); // obsoleted code
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] imageInByte = stream.toByteArray();
...
尝试直接转换位图=((BitmapDrawable)d).getBitmap()代码>@RethinavelPillai我试过了。但我也犯了同样的错误