javalibgdxpngpixmap

How to get int values for each pixel from a pixmap in libgdx


I'm trying to open a PNG file and display the value of each pixel.

Pixmap pixmap = new Pixmap(new FileHandle("images/Laby0.png"));

int widthPixmap = pixmap.getWidth();
int heightPixmap = pixmap.getHeight();

for(int y=0; y < heightPixmap; y++){
    for(int x=0; x < widthPixmap; x++){
        int color = pixmap.getPixel(x, y);
        System.out.println("X : "+ x + " y : " + y + " color = " +color);
    }
}

The PGN file has only some white, black and levels of gray, but the output are values like -256, and -1!

Why does it not give positive values ?


Solution

  • Colors returned by pixmap.getPixel are 32 bit RGBA packed integers. But Java uses signed integers. If the R component is bigger than 127 out of 255, then the first bit will be a 1, meaning the signed interpretation of the whole 32 bit number will be negative.

    It doesn't really matter anyway, because the single number representation is not comprehensible as a color. You probably will want to convert it to hexadecimal so you can read it and make sense of it:

    String hexColor = Integer.toHexString(color);
    

    If you'd like to read the separate components as numbers from 0 to 255, you can mask out the part you want and shift the 8 bits of interest to the least significant part of the 32 bits:

    int red = color >>> 24;
    int green = (color & 0xFF0000) >>> 16;
    int blue = (color & 0xFF00) >>> 8;
    int alpha = color & 0xFF;