androidcolormatrix

How do I convert a Bitmap with black pixels to another color in Android?


I've got a Bitmap with some transparent pixels and rest is mainly black (some black pixels possibly have a few sem-transparent pixels).

I need to re-use these bitmaps and want to be able to essentially create a Mask out of this bitmap at runtime and then try and blend with a block of another color (like Red, green etc) so that the end result is the same image but with red color (and those pixels which were semi-transparent black pixels turn into semi-transparent red pixels).

I've tried all sorts of color filters and xfermodes but have not been able to figure out. Please help!


Solution

  • If you doesn't need high speed, you can use simple solution by manually blend pixels.

    final Bitmap bmp = /* there your bitmap */;
    
    int w = bmp.getWidth();
    int h = bmp.getHeight();
    
    for (int x = 0; x < w; x++) {
      for (int y = 0; y < h; y++) {
        int color = bmp.getPixel(x, y);
    
        // Shift your alpha component value to the red component's.
        color = (color << 24) & 0xFF000000;
    
        bmp.setPixel(x, y, color);
      }
    }
    

    If you need more effective processing, you must use (at least) getPixels method or, more preferable, native processing.