Understanding the function of CheckAlpha boolean PGraphics argument

I am trying to figure out what the CheckAlpha argument to Pgraphics does - and how and why - and have chased my confusion down to line 281 of LINK UPDATED the core docs

   if ((pixels[i] & 0xff000000) != 0xff000000)

It’s checking for transparency, and setting the mode to ARGB if it finds it. But:

  • why is it checking for transparency?
  • how does this conditional work?

It’s ANDing the value of the pixel with a hex value, and checking that the result isn’t that value. Somehow, this tells you about whether there is transparency.

Can someone unpack this for me?

thannks!

Color in encoded in a 32 bit integer 8 bits for each channel alpha, red, green and blue like this

0xAARRGGBB

Now if we perform the AND in the conditional we are doing

     0xAARRGGBB
&    0xFF000000 we get
     0xAA000000

All the bits in the RGB chanels become 0 but the bits in the alpha channel are unchanged.

If fact the conditional statement is checking that the alpha channel is 0xFF in other words fully opaque.

No idea the link didn’t work :wink:

1 Like

Tx let me check the link and fix if I can - UPDATE: link fixed
Basically it seems to be bailing out silently if it detects transparency?

  /**
   * Check the alpha on an image, using a really primitive loop.
   */
  private void checkAlpha() {
    if (pixels == null) {
      return;
    }

    for (int i = 0; i < pixels.length; i++) {
      // since transparency is often at corners, hopefully this
      // will find a non-transparent pixel quickly and exit
      if ((pixels[i] & 0xff000000) != 0xff000000) {
        format = ARGB;
        break;
      }
    }
  }

The PImage constructor initializes the format attribute to RGB and this method changes the format attribute to ARGB if it finds a pixel with transparency i.e. 0xAA != 0xFF

Obviously some other methods in this class need to be aware of format for their implementation

It is also a private function so we can’t use it directly.

1 Like