[英]Android : Error in getting URI of an image
在我的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);
但是原木貓說
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 強制轉換為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();
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.