Im trying to convert the pixels that i get from the getRGB function of a black and white image to unsigned byte, I have read and, correct if I am wrong, the getRGB function in java returns integer values, so what I want to do is to see values from 0-255 not the negative integer values Im getting with the function. I have tried this with no sucess:
int width;
int height;
byte extract;
int asign;
int matrix[][];
for ( i = 0; i < height; i++)
{
for ( j = 0; j < width; j++)
{
extract =(byte)(xray.getRGB(j, i));
asign = (int)extract;
//asign = asign & 0xff;
asign = asign + 128;
matrix[i][j] = asign;
}
}
Notice that xray is a buferred image. Hope you can help me with this issue guys. As you can see I've tried with mask, also I 've tried trying to add 128 to the value after the cast.
Well, getRGB()
returns a signed int
, but it's a 32-bit int
representing the alpha and R, G, B values. The most significant byte is alpha, and if it's fully opaque then that will be 255, which means you'll end up with a negative int
overall.
If you want to mask out the alpha value, you can do it with
matrix[i][j] = xray.getRGB(j,i) & 0xFFFFFF;
which will get rid of the high-order byte. This will leave you with a single positive value containing the RGB values for the pixel.
Careful what you do with it afterwards: if you then try to use it to set the colour of a pixel later, you might end up setting the alpha value to 0 (now that you've masked it off), and so you'll end up with something fully transparent (aka invisible).
If it's a black and white image and for some reason you're getting just values from -128 to 127, then more or less the same trick applies to make it unsigned. In fact exactly the same line as above would do it, but you could also shorten the mask:
matrix[i][j] = xray.getRGB(j,i) & 0xFF;
This means you don't need any if
-else
in your code to get it working, and you don't need your extract
or asign
variables.