Java 如何从drawable加载图像并转换为位图

Java 如何从drawable加载图像并转换为位图,java,android,image,bitmap,drawable,Java,Android,Image,Bitmap,Drawable,我在drawable文件夹中有一个图像,我想转换为位图,然后转换为字节[]以存储到数据库中,我可以将位图转换为字节数组,但无法从drawable中获取图像,因为bitmap photo=BitmapFactory.decodeResource(getResources(),R.drawable.image)返回null。怎么做 我现在有什么 Bitmap photo = BitmapFactory.decodeResource(getResources(), R.drawable.image);

我在drawable文件夹中有一个图像,我想转换为位图,然后转换为字节[]以存储到数据库中,我可以将位图转换为字节数组,但无法从drawable中获取图像,因为
bitmap photo=BitmapFactory.decodeResource(getResources(),R.drawable.image)返回null。怎么做

我现在有什么

Bitmap photo = BitmapFactory.decodeResource(getResources(), R.drawable.image); //this returns null
if(photo != null)
byte[] bytes = getBitmapAsByteArray(photo);

//this works
DatabaseHelper databaseHelper = new DatabaseHelper(this);
databaseHelper.add("DEFAULT",bytes);
更新: 当我使用
photo.setImageBitmap(位图)将位图设置为image时从数据库检索信息后,它不会出现,似乎存储不起作用

我正在像这样将信息存储到数据库中

private static byte[] getBitmapAsByteArray(Bitmap bitmap) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 0, outputStream);
        return outputStream.toByteArray();
    }

public boolean addUserInformation(String username, byte[] picture){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("USERNAME", username);
        if(picture!=null) {
            values.put("PICTURE", picture);
        }
        id = db.insert(TABLE_NAME1, null, values);
        }
        db.close();
        if(id == -1)
            return false;
        else
            return true;
    }
Cursor data = databaseHelper.getUserInformation();
        if(data.moveToFirst()) {
            mUsername = data.getString(1);
            bytes = data.getBlob(2);
            if(bytes!=null)
                profilePhoto = BitmapFactory.decodeByteArray(bytes, 0, data.getBlob(2).length);
        }
检索这样的信息

private static byte[] getBitmapAsByteArray(Bitmap bitmap) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 0, outputStream);
        return outputStream.toByteArray();
    }

public boolean addUserInformation(String username, byte[] picture){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("USERNAME", username);
        if(picture!=null) {
            values.put("PICTURE", picture);
        }
        id = db.insert(TABLE_NAME1, null, values);
        }
        db.close();
        if(id == -1)
            return false;
        else
            return true;
    }
Cursor data = databaseHelper.getUserInformation();
        if(data.moveToFirst()) {
            mUsername = data.getString(1);
            bytes = data.getBlob(2);
            if(bytes!=null)
                profilePhoto = BitmapFactory.decodeByteArray(bytes, 0, data.getBlob(2).length);
        }
在数据库类中使用getUserInformation()

public Cursor getUserInformation(){
        SQLiteDatabase db = this.getReadableDatabase();
        String query = "SELECT * FROM " + TABLE_NAME1;
        Cursor c = db.rawQuery(query,null);
        return c;
    }
用这个

位图照片=((BitmapDrawable)getDrawable(R.drawable.R.drawable.image)).getBitmap()


希望工作顺利;)

以下方法应该可以正常工作:

public static Bitmap getBitmapFromVectorDrawable(Context context, int drawableId) {
    Drawable drawable = ContextCompat.getDrawable(context, drawableId);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        drawable = (DrawableCompat.wrap(drawable)).mutate();
    }
    Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
            drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    drawable.draw(canvas);
    return bitmap;
}
build.gradle(应用程序级)

或者,您也可以像这样在Kotlin中使用
android ktx
,它适用于
Drawable
的任何子类:

build.gradle

dependencies {
    implementation 'androidx.core:core-ktx:1.0.0-alpha1'
}
然后像这样使用
Drawable#toBitmap()

val bitmap = AppCompatResources.getDrawable(requireContext(), drawableId).toBitmap() 

你可以用一种非常简单的方法来做。将Glide添加到项目中,如下所示-

implementation 'com.github.bumptech.glide:glide:4.9.0'
然后取一个全局位图变量,如下调用-

私有位图

Glide.with(this)
        .asBitmap()
        .load(R.drawable.image)
        .into(new CustomTarget<Bitmap>() {
            @Override
            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                imageView.setImageBitmap(resource);
                //Save the bitmap to your global bitmap
                imageBitmap = resource;
            }

            @Override
            public void onLoadCleared(@Nullable Drawable placeholder) {
            }
        });
Glide.with(这个)
.asBitmap()
.load(R.drawable.image)
.into(新的CustomTarget(){
@凌驾

公共资源就绪(@NonNull位图资源,@Nullable Transitioncrash with android.graphics.drawable.VectorDrawable不能强制转换为android.graphics.drawable.BitmapDrawable。它还需要api级别21,有没有办法也包括旧的api?它应该只在drawable已经是
BitmapDrawable
时工作。应该在
ClassCastExceptio时崩溃。)n
在所有其他情况下,当可绘制对象不是
BitmapDrawable
,例如
VectorDrawable
LayerDrawable
ScaleDrawable
等时,无法识别它给我的BitmapDescriptor类无法解析符号,我应该导入哪个库?@james,然后使用
AppCompatResources
这一行中的
ContextCompat
的:
Drawable-Drawable=AppCompatResources.getDrawable(context,drawableId);
为什么要“转换”
VectorDrawable
到原始像素?VectorDrawable
的主要目的是避免光栅化图形,而不是直接使用矢量图形。我需要将图像作为字节数组存储到SQLite数据库中。那么为什么要使用
VectorDrawable
呢?我应该使用什么从drawable文件夹中获取.xml图像并将其转换到字节数组?@pskink