Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change color of bitmap

I'm trying to create a function that gets a bitmap and destiny color and returns the colored bitmap (without using paint). I found few ways of doing it but nothing works like I want it to.

The closest solution I was able to find is:

    public static Bitmap changeImageColor(Bitmap srcBmp, int dstColor) {

        int width = srcBmp.getWidth();
        int height = srcBmp.getHeight();

        float srcHSV[] = new float[3];
        float dstHSV[] = new float[3];

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

        for (int row = 0; row < height; row++) {
            for (int col = 0; col < width; col++) {
                Color.colorToHSV(srcBmp.getPixel(col, row), srcHSV);
                Color.colorToHSV(dstColor, dstHSV);

                // If it area to be painted set only value of original image
                dstHSV[2] = srcHSV[2];  // value
                int color2=Color.HSVToColor(dstHSV);;
                dstBitmap.setPixel(col, row, Color.HSVToColor(dstHSV));
            }
        }

        return dstBitmap;
    }

but It doesn't work very well on transparent images as can be seen here (before and after): enter image description here

Anyone has any other solutions (again without using paint at all)?

like image 490
SpoocyCrep Avatar asked Jan 19 '15 12:01

SpoocyCrep


1 Answers

You just need to extract alpha and re-apply it after transformation. And use ARGB_8888;

Edited your code to include alpha:

public Bitmap colorize(Bitmap srcBmp, int dstColor) {

        int width = srcBmp.getWidth();
        int height = srcBmp.getHeight();

        float srcHSV[] = new float[3];
        float dstHSV[] = new float[3];

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

        for (int row = 0; row < height; row++) {
            for (int col = 0; col < width; col++) {
                int pixel = srcBmp.getPixel(col, row);
                int alpha = Color.alpha(pixel);
                Color.colorToHSV(pixel, srcHSV);
                Color.colorToHSV(dstColor, dstHSV);

                // If it area to be painted set only value of original image
                dstHSV[2] = srcHSV[2];  // value
                dstBitmap.setPixel(col, row, Color.HSVToColor(alpha, dstHSV));
            }
        }

        return dstBitmap;
}
like image 176
SGal Avatar answered Oct 05 '22 11:10

SGal