JayJona
JayJona

Reputation: 502

How to load an image from drawable and convert to a bitmap

I have an image in the drawable folder and I want to convert into a bitmap and then convert to byte[] to store into a database, I can convert the bitmap to a byte array but I'm not able to get the image from drawable since Bitmap photo = BitmapFactory.decodeResource(getResources(), R.drawable.image); returns null. How to do it?

what i have for the moment

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

UPDATE: when I set the bitmap to image with photo.setImageBitmap(bitmap); after it retrieves information from database it does not appear, seems that the store does not work

I'm storing info into database like this

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;
    }

and retrieve information like this

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

with getUserInformation() inside database class

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

Upvotes: 3

Views: 10174

Answers (3)

Anupam
Anupam

Reputation: 2853

You can do this in a very simple way. Add Glide to your project like this -

implementation 'com.github.bumptech.glide:glide:4.9.0'

Then take a global Bitmap variable and call like this-

private Bitmap imageBitmap;

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) {
            }
        });

Now pass the imageBitmap to your getBitmapAsByteArray() to convert to byteArray, so that you can save this in your SQLite Database.

Hope it helps!

Upvotes: 0

SaadAAkash
SaadAAkash

Reputation: 3193

The following method should work fine:

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 (project-level)

dependencies {
        classpath 'com.android.tools.build:gradle:2.2.0-alpha5'
    }

build.gradle (app-level)

android {
    compileSdkVersion 23
    buildToolsVersion '23.0.3'
    defaultConfig {
        minSdkVersion 16
        targetSdkVersion 23
        vectorDrawables.useSupportLibrary = true
    }
    ...
}
...

Or, you can use android-ktx in Kotlin too like this which works for any subclass of Drawable:

build.gradle

dependencies {
    implementation 'androidx.core:core-ktx:1.0.0-alpha1'
}

Then use Drawable#toBitmap() like this:

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

Upvotes: 5

Ali Amini
Ali Amini

Reputation: 416

Use This

Bitmap photo = ((BitmapDrawable) getDrawable(R.drawable.R.drawable.image)).getBitmap();

hopefully, work fine ;)

Upvotes: 1

Related Questions