繁体   English   中英

Android:获取图像的URI时出错

[英]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.

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