gpt4 book ai didi

java - 安卓 : Error in getting URI of an image

转载 作者:行者123 更新时间:2023-12-01 13:51:27 24 4
gpt4 key购买 nike

在我的 Android 应用程序中有一个 ImageView 。我需要获取此图像并将其保存在 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();

...

关于java - 安卓 : Error in getting URI of an image,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19922998/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com