Convert RGB to HSV in android

Tags: , , ,



I want to get the ARGB values from a pixel and convert to HSV and then set the pixel with the new values.

I don’t fully understand how to do that. Can anyone help me?

Answer

Let’s say you have a Bitmap object and x and y co-ordinates. You can get the color from the bitmap as a 32-bit value like this:

int color = bitmap.getPixel(x, y);

You can separate out the argb components like this:

int a = Color.alpha(color);
int r = Color.red(color);
int g = Color.green(color);
int b = Color.blue(color);

Then you can convert to HSV like this:

float[] hsv = new float[3];
Color.RGBToHSV(r, g, b, hsv);

Now you can manipulate the HSV values however you want. When you are done you can convert back to rgb:

color = Color.HSVToRGB(hsv);

or like this is you want to use the alpha value:

color = Color.HSVToRGB(a, hsv);

Then you can write the color back to the bitmap (it has to be a mutable Bitmap):

bitmap.setPixel(x, y, color);


Source: stackoverflow