2

I am getting the current wallpaper by using following code:

  final WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
  final Drawable wallpaperDrawable = wallpaperManager.getDrawable();

How can I create a bitmap from this?

like when I create a bitmap from res folder I use this

    Resources res = getApplicationContext().getResources();
    b = BitmapFactory.decodeResource(res, R.drawable.wall);

What code I should use to get current wallpaper into the bitmap so I can draw it on my canvas and use it as my live wallpaper background?

Piyush
  • 1,744
  • 1
  • 15
  • 28
Badal
  • 3,738
  • 4
  • 33
  • 60

1 Answers1

4

The Drawable fetched should really be a BitmapDrawable. You can verify this using instanceof if necessary.

That being the case, all you have to do is:

final Drawable wallpaperDrawable = wallpaperManager.getDrawable();
final Bitmap wallpaperBitmap = ((BitmapDrawable) wallpaperDrawable).getBitmap();

EDIT: If it turns out that the Drawable is NOT a BitmapDrawable, you can use the following method to convert it (found in this answer, credit to André):

public static Bitmap drawableToBitmap(Drawable drawable) {
    if (drawable instanceof BitmapDrawable) {
        return ((BitmapDrawable)drawable).getBitmap();
    }

    Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap); 
    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    drawable.draw(canvas);

    return bitmap;
}
Community
  • 1
  • 1
Cat
  • 66,919
  • 24
  • 133
  • 141