简体   繁体   中英

Detecting if a BufferedImage contains transparent pixels

I'm trying to optimise a rendering engine in Java to not draw object's which are covered up by 'solid' child objects drawn in front of them, ie the parent is occluded by its children.

I'm wanting to know if an arbitrary BufferedImage I load in from a file contains any transparent pixels - as this affects my occlusion testing.

I've found I can use BufferedImage.getColorModel().hasAlpha() to find if the image supports alpha, but in the case that it does, it doesn't tell me if it definitely contains non-opaque pixels.

I know I could loop over the pixel data & test each one's alpha value & return as soon as I discover a non-opaque pixel, but I was wondering if there's already something native I could use, a flag that is set internally perhaps? Or something a little less intensive than iterating through pixels.

Any input appreciated, thanks.

Unfortunately, you will have to loop through each pixel (until you find a transparent pixel) to be sure.

If you don't need to be 100% sure, you could of course test only some pixels, where you think transparency is most likely to occur.

By looking at various images, I think you'll find that most images that has transparent parts contains transparency along the edges. This optimization will help in many common cases.

Unfortunately, I don't think that there's an optimization that can be done in one of the most common cases, the one where the color model allows transparency, but there really are no transparent pixels... You really need to test every pixel in this case, to know for sure.

Accessing the alpha values in its "native representation" (through the Raster / DataBuffer / SampleModel classes) is going to be faster than using BufferedImage.getRGB(x, y) and mask out the alpha values.

I'm pretty sure you'll need to loop through each pixel and check for an Alpha value.

The best alternative I can offer is to write a custom method for reading the pixel data - ie your own Raster . Within this class, as you're reading the pixel data from the source file into the data buffer, you can check for the alpha values as you go. Of course, this isn't much help if you're using a built-in image reading class, and involves a lot more effort.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM