Java – Use functions to change bitmap colors

Use functions to change bitmap colors… here is a solution to the problem.

Use functions to change bitmap colors

I need a function to get the bitmap and return the bitmap with the changed color. It needs to be quick and simple.

Its purpose is to change color, and it is also a PNG with alpha.

I’ve seen it online, but I can’t use Canvas or anything external. The function resides in an external object (don’t ask…).

This is something I’ve tried so far (it didn’t work). I know I’m really close, just tidying up the color matrix and letting alpha work.

public Bitmap changeBitmapColor(Bitmap sourceBitmap, int deg)
{   
    int width, height;
    height = sourceBitmap.getHeight();
    width = sourceBitmap.getWidth();    

Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);

Canvas c = new Canvas(bmpGrayscale);
    Paint paint = new Paint();

figure out color matricies.
    ColorMatrix cm = new ColorMatrix();

cm.setSaturation(0);

cm.set(new float[] 
    {
            0, 0, 0, 0, 0,
            0, 1, 0, 0, 0,
            0, 0, 255, 0, 0,
            0, 0, 0, 1, 0,
            0, 0, 0, 0, 1
         }); 

ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
    paint.setColorFilter(f);

c.drawBitmap(sourceBitmap, 0, 0, paint);

return bmpGrayscale;
}

Any help would be great!

——– Fixed ——–

I’ve solved this by changing the color matrix, now the bitmap will change the color and not show the alpha value.

The first is the matrix:

    cm.set(new float[] 
    {
            0, 0, 0, 0, 0,
            0, 1, 0, 0, 0,
            0, 0, 140, 0, 0,
            0, 0, 0, 1, 0,
            0, 0, 0, 0, 1
    }); 

The second thing I have to change is this line of code:

Bitmap newBM = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);

Good luck readers!

Solution

I don’t see why standalone excludes using Canvas. You can create a new Bitmap, create a Canvas to draw in, and then draw the original Bitmap with a Paint with a color filter set (using setColorFilter). PorterDuffColorFilter Classes may help with this.

Related Problems and Solutions