# Setting pixel colour

## Recommended Posts

I want to change the hue of a bitmap based on an RGB colour value but i can't quite get it. My program reads in an image in greyscale then changes the hue (as well as saturation and brightness) based on a colour. So the user can select a colour (say red or green, or even something like brown which has less than 100% saturation) and the image is displayed in that colour. Now, i'm no expert on colour but i think what i should do is set the hue of the pixels to that of the colour then i need to add the sat of the colour to that of the pixel then adjust it a bit. But how? This is what i have so far:

`int col = 0, alp = 0;float hsbP[], hsbB[];  // HSB values for image pixel colour and ball colourhsbB = Color.RGBtoHSB(c.getRed(), c.getGreen(), c.getBlue(), null);for (int y = 0; y < img.getHeight(); y++) {   for (int x = 0; x < img.getWidth(); x++) {       col = img.getRGB(x, y);       if (col != 0) {   // Only set pixel if it's not transparent           alp = col >> 24;           hsbP = Color.RGBtoHSB(col>>16 & 0x0000FF, col>>8 & 0x0000FF, col & 0x0000FF, null);           hsbP[0] = hsbB[0];    // Set each pixel's hue to that of the ball           hsbP[1] = (hsbP[1] + hsbB[1])/2.0f; // Set average saturation           hsbP[2] = (hsbP[2] + hsbB[2])/2.0f;           col = Color.HSBtoRGB(hsbP[0], hsbP[1], hsbP[2]);           img.setRGB(x, y, (alp << 24) | col);       }   }}`

The problem is that with, say, red (255, 0, 0) the image is red but only 1/2 sat because i divide by 2. (H, S and B values are between 0.0 and 1.0). The colour has S=1.0 so the image needs to be between 0.0 and 1.0. Whereas if the colour had S=0.5, then the pixels would be 0.0 <= S <= 0.5. Is that right?

Also, i can't get alpha right. Variable alp stores the alpha value (since HSB has no alpha) then writes it back to the pixel colour. Does that look right? I'm using Java which should use 32bit integers, but i'm not sure how many bits it uses for RGB.

EDIT: i just looked at the image properties and it says it uses sRGB colour (the image is PNG format). And apparently, Java cannot recognise the format. What exactly is sRGB and where is the alpha? Is it premultiplied?

Edited by Haro
##### Share on other sites

Ok, i fixed the hue problem. At first i realized that i needed to multiply saturation and brightness so that the image can have a minimum brightness of 0 and a max of whatever the brightness of the colour is. But that didn't work. All i got was a grey image. Then i realized that the greyscale image always has a saturation of 0. So i set the sat of the image to that of the colour and everything works fine

`hsbP[0] = hsbB[0];    // Set each pixel's hue to that of the ballhsbP[1] = hsbB[1];hsbP[2] = hsbP[2] * hsbB[2];`

I still have the problem of alpha but i think that's just a matter of finding out what format the image is stored as internally, and how many bits it uses for alpha.

×