Search code examples
javaimage-processingrgbpixelbufferedimage

get rgb using shift register java


i have this code from other place, but i still confuse about

  final byte[] pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
  int[][] result = new int[height][width];
    int k = 0;
    final int pixelLength = 3;
    for (int pixel = 0, row = 0, col = 0; pixel < pixels.length; pixel += pixelLength)           {
       int argb = 0;
       int blue= (((int) pixels[pixel] & 0xff));
       argb = argb + blue;
       int green = (((int) pixels[pixel + 1] & 0xff) << 8);
       argb = argb + green;  // green)
       int red = (((int) pixels[pixel + 2] & 0xff) << 16);
       argb = argb + red; 
       result[row][col] = argb;
       k++;
       col++;
       if (col == width) {
           col = 0;
           row++;
       }

     }

when i print red, green ,blue why it not print the rgb value ? can someone explain to me ? what meaning of pixels[pixel] & 0xff ? thx alot before :D


Solution

  • What this is doing is converting 3 bytes to a single int. The reason why pixels[pixel] & 0xff is used is that it converts signed values to unsigned values. This is necessary because java doesn't have an unsigned type, and thus what would normally be an RGB value of 200 is actually something else.

    The purpose of the shifts is to put the 3 values in the same place, so that the value is them next to each other.