parameter
parameter

Reputation: 904

Programatically get Android package icon as PNG or BMP

I'm attempting to save all of the icons of the packages on a device as a BMP or PNG file by iterating through each package and doing the following.

Drawable icon = getPackageManager().getApplicationIcon(packageInfo);
Bitmap bitmap = Bitmap.createBitmap(icon.getIntrinsicWidth(), icon.getIntrinsicHeight(), Config.ARGB_8888);

try {
     out = new FileOutputStream("/storage/sdcard0/images/" + packageInfo.packageName +".png");
     bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
} catch (Exception e) {
     e.printStackTrace();
} finally {
    try{
     out.close();
    } catch(Throwable ignore) {}
}

This is creating blank images though, how would I change my code to create the actual icon in an image format?

enter image description here

Upvotes: 2

Views: 3026

Answers (2)

Rajeev Chitturi
Rajeev Chitturi

Reputation: 41

Below is the code that could cover all the cases.

public static Bitmap drawableToBitmap (Drawable drawable) {


    if (drawable instanceof BitmapDrawable) {
        BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
        if (bitmapDrawable.getBitmap() != null) {
            return bitmapDrawable.getBitmap();
        }
    }

    if (drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {
        return Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); // Single color bitmap will be created of 1x1 pixel
    } else {
        return Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
    }

}

Upvotes: 2

user3509128
user3509128

Reputation: 142

My issue was this if anyone has the same problem, I referenced this answer.

I forgot to check to see if the icon was already an instance of BitmapDrawable. Because it was I could just cast it to a bitmapdrawable and use .getBitmap

if (icon instanceof BitmapDrawable) {
    bitmap = ((BitmapDrawable)icon).getBitmap();
}else{
    bitmap = Bitmap.createBitmap(icon.getIntrinsicWidth(), icon.getIntrinsicHeight(), Config.ARGB_8888);
}

Upvotes: 2

Related Questions