0

I want to grayscale a drawable. I'm trying what Justin suggested, but it isn't working on Donut (1.6) and Eclair (2.1). It works on Android 2.2+. The code I'm trying is the following:

ColorMatrix matrix = new ColorMatrix();
matrix.setSaturation(0);
ColorMatrixColorFilter filter = new ColorMatrixColorFilter(matrix);
drawable.setColorFilter(filter);

Any clues?

Community
  • 1
  • 1
Rafael
  • 6,339
  • 5
  • 22
  • 22
  • "Isn't working", "Isn't working", "Isn't working".... **What** isn't working? Do you get an error? Is it showing with colors? Or what? – Simon Forsberg Jul 29 '13 at 12:31

1 Answers1

1

This works for Lower Api, try it

 public Bitmap toGrayscale(Bitmap bmpOriginal)
    {        
        int width, height;
        height = bmpOriginal.getHeight();
        width = bmpOriginal.getWidth();    

        Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        Canvas c = new Canvas(bmpGrayscale);
        Paint paint = new Paint();
        ColorMatrix cm = new ColorMatrix();
        cm.setSaturation(0);
        ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
        paint.setColorFilter(f);
        c.drawBitmap(bmpOriginal, 0, 0, paint);
        return bmpGrayscale;
    }

If you want to use a canvas or a painter use this code, you can't get a grayscale image for your code because you used an immutable drawable

Bitmap immutableBitmap = BitmapFactory.decodeResource(getResources(), 
    R.drawable.my_drawable);
Bitmap mutableBitmap = immutableBitmap.copy(Bitmap.Config.ARGB_8888, true);

//you have two bitmaps in memory, so clean up the mess a bit
immutableBitmap.recycle(); immutableBitmap=null;

Drawable d = new BitmapDrawable(mutableBitmap);

//mutate it
d.setColorFilter(new LightingColorFilter(color, lightenColor));

imageView.setImageDrawable(d);
K_Anas
  • 31,226
  • 9
  • 68
  • 81
  • 1
    The first code worked for me. Instead of `Bitmap.Config.RGB_565` I put `Bitmap.Config.ARGB_8888` to get transparency. The second isn't working... – Rafael Jun 06 '12 at 02:06