In the code below (in the else statement) I am trying to get the value for the red blue and green parts of the given pixel. I am not sure how to get the value from the int. This code is from another stack post Java - get pixel array from image I am trying to modify it to tell me if it has found a pixel of a specific color (I know the RGB of this color and want to compare each pixel).
How can I get each R, G, and B in the 0-255 value range?
private static int[][] convertBImageToArr(BufferedImage image)
{
final byte[] pixels;
DataBuffer rasterData = image.getRaster().getDataBuffer();
DataBufferByte rasterByteData = (DataBufferByte)rasterData;
pixels = rasterByteData.getData();
final int width = image.getWidth();
final int height = image.getHeight();
final boolean hasAlphaChannel = image.getAlphaRaster() != null;
int[][] result = new int[height][width];
if (hasAlphaChannel)
{
final int pixelLength = 4;
for(int pixel = 0, row = 0, col = 0; pixel < pixels.length; pixel += pixelLength)
{
int argb = 0;
argb += (((int) pixels[pixel] & 0xff) << 24); // alpha
argb += ((int) pixels[pixel + 1] & 0xff); // blue
argb += (((int) pixels[pixel + 2] & 0xff) << 8); // green
argb += (((int) pixels[pixel + 3] & 0xff) << 16); // red
result[row][col] = argb;
col++;
if (col == width)
{
col = 0;
row++;
}
}
}
else
{
final int pixelLength = 3;
for (int pixel = 0, row = 0, col = 0; pixel < pixels.length; pixel += pixelLength)
{
int argb = 0;
argb += -16777216; // 255 alpha
argb += ((int) pixels[pixel] & 0xff); // blue
argb += (((int) pixels[pixel + 1] & 0xff) << 8); // green
argb += (((int) pixels[pixel + 2] & 0xff) << 16); // red
if(row == 11 && col == 11)
{
System.out.println("B:" + ((int) pixels[pixel] & 0xff));
System.out.println("G:" + (((int) pixels[pixel + 1] & 0xff) << 8));
System.out.println("R:" + (((int) pixels[pixel + 2] & 0xff) << 16));
}
result[row][col] = argb;
col++;
if (col == width)
{
col = 0;
row++;
}
}
}
return result;
}