Search code examples
javaimage-processingalphais-empty

Detect Empty Pixel From File


For full Project check repo here. Feel free to clone and run. Note the test images https://github.com/AshGale/Image2RGBA

When Reading in a PNG that has sections shown as empty(hashed) in GIMP, the values read into the program are [0,0,0,255](Red, Green, Blue, Alpha). I expect the empty bit to have Alpha 0 therefore fully empty [0,0,0,0]. However the value is [0,0,0,255] witch is also Full Black.

  1. Question, how can I check in java if a pixel is completely empty, ie hashed in gimp.

  2. how can i then write this to an image file with a bufferedImage.

  3. Should the alpha value be 0 for an image with empty as shown in image? please suggest way to read in file or file format.

    //Code Extract See Git for full code

...

for (int i = 0; i < imageHeight; i++) {
    for (int j = 0; j < imageWidth; j++) {

    individualPixel = new Color(buffImage.getRGB(j, i));

    //TODO find a way to detect a empty pixel an keep perfect black
    if(individualPixel.getRed() == 0 
            && individualPixel.getGreen() == 0
            && individualPixel.getBlue() ==0
            ) {                             

        //set pixel at location to empty
        buffRed.setRGB(j, i, getIntFromColor(0, 0, 0, 0));
        buffGreen.setRGB(j, i, getIntFromColor(0, 0, 0, 0));
        buffBlue.setRGB(j, i, getIntFromColor(0, 0, 0, 0));
    }else {
        // RED
        tempPixel = new Color(individualPixel.getRed(), 0, 0, individualPixel.getAlpha());
        buffRed.setRGB(j, i, getIntFromColor(tempPixel.getRed(), 0, 0, tempPixel.getAlpha()));

        // GREEN

        // BLUE
    }

...

ImageIO.write(buffRed, "png", redImg);

enter image description here


Solution

  • I believe the problem in your original code is simply this line:

    individualPixel = new Color(buffImage.getRGB(j, i));
    

    This Color constructor effectively discards the alpha component. JavaDoc says (emphasis mine):

    Creates an opaque sRGB color with the specified combined RGB value [...] Alpha is defaulted to 255.

    Instead it should be:

    individualPixel = new Color(buffImage.getRGB(j, i), true); // hasAlpha = true
    

    This constructors JavaDoc says:

    Creates an sRGB color with the specified combined RGBA value [...] If the hasalpha argument is false, alpha is defaulted to 255.

    You shouldn't really have to use the alpha raster (not all BufferedImages have one) to achieve this, and avoiding it is both simpler and more compatible.

    Finally, the R, G and B values of a fully transparent pixel doesn't really matter. So testing whether it is all black may be a too strict check (although it does seem to work fine for your input image).

    PS: I think a more precise terminology would be "transparent", instead of "empty".