0

在我的 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);
4

1 回答 1

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();

    ...
于 2013-11-12T09:41:31.603 回答