在下面的代码中(在 else 语句中),我试图获取给定像素的红色蓝色和绿色部分的值。我不确定如何从 int 中获取值。这段代码来自另一个堆栈后Java - 从图像中获取像素数组我正在尝试修改它以告诉我它是否找到了特定颜色的像素(我知道这种颜色的 RGB 并想比较每个像素)。
如何获得 0-255 值范围内的每个 R、G 和 B?
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;
}