Search code examples
javapngpixel

How to make pixel be in range [1-255] in java in matrix form (x-y plane)?


I have an image of (512 pixels * 512 pixels) of type PNG. I knew that each pixel is of type 8 bits. So, we have range [0-255]. the question is I want the row and column of this image such that the each cell has a number in between [0-255].

Unfortunately, my program works fine without error, but the bad news is that it doesn't come with what I want. the output for each cell there is 7 numbers i.e. 2894893 -2829100 -2829100 -2894893 -2894893 -2960686 -2960686 -2960686 -3092272 -3223858 -3289651 -3421237 -4144960 -3684409 -3552823 -4144960 -4802890 -5263441 etc.

what I want is only a range between [1-255]? i.e. instead of the above output, we should have something like 23 182 33 250 etc.

remember that I need this using 2-dimensional instead of 1-dimensional (means array[row] [column] instead of array [index]). Here is the code:

 ima = ImageIO.read(new File("how.png"));

    int [] pix = ima.getRGB(0, 0, ima.getWidth(), ima.getHeight(), null, 0, ima.getWidth());

    int count=0;        
    for (int i=0; i < ima.getHeight() ; i++)
    {
        for (int j=0; j < ima.getWidth() ; j++){
            System.out.print(pix[count]+" ");
            count++;
        }
        System.out.println();

    }

This method is taken from the member @davenpcj from getting pixel data from an image using java.

Thank you


Solution

  • What you are getting are RGB values, where each of the three components is stored as a byte. That is, the integer consists of 4 bytes, each one for the R, G, B and alpha components of the pixel. For example, the pixel value 2894893 looks like this as binary:

     00000000 00101100 00101100 00101101
    

    You can get the individual channels by masking the integer pixel value:

    int red = (pix[count] & 0xFF);
    int green = (pix[count] >> 8) & 0xFF;    
    int blue = (pix[count] >> 16) & 0xFF;
    int alpha = (pix[count] >> 24) & 0xFF;