简体   繁体   中英

Android : Error in getting URI of an image

In my Android application there is an image view. I need to get this image and save it in the sqlite database. I've tried to get uri of the image and save it in the database. I've used following code segment to get the uri of the image.

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

But log cat says

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

Error is pointed to this line.

BitmapDrawable bitDw = ((BitmapDrawable) d);

The problem is stated in the ClassCastException , you cannot cast a GradientDrawable into a BitmapDrawable .

Here is the workaround for it:

    ...

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

    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM