在我的Android应用程序中有一个图像视图。我需要获取此图像并将其保存在sqlite数据库中。我试图获取图像的uri并将其保存在数据库中。我已经使用以下代码段来获取图像的uri。
// 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);
但是log cat说
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);
答案 0 :(得分:1)
问题在 ClassCastException 中说明,您无法将 GradientDrawable 强制转换为 BitmapDrawable 。
以下是解决方法:
...
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();
...