Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java check if an image has transparency

Is it possible to check if png image has transparency in Java? I need to convert all png images to jpg if png image doesn't contain transparency. Is there method in Java to check this?

like image 946
newbie Avatar asked Apr 19 '12 07:04

newbie


People also ask

How can I tell if an image has a transparent background?

Images that have transparency often illustrate it by using a gray and white checkered pattern. The idea is that you can see which parts of the image will be transparent before you save it. The checkered pattern is the background.

How do I know a PNG is transparent?

png” odds are good(but not 100% guaranteed) that it is transparent. The only sure-fire way to tell is to open it in a photo editor(or another program that allows layers of some type) and place it on a layer above something else. If you can see the background it's transparent.


1 Answers

You can check if the image's color model includes an alpha channel:

BufferedImage img = ImageIO.read(/* from somewhere */);

if (img.getColorModel().hasAlpha()) {
    // img has alpha channel
} else {
    // no alpha channel
}

Note that This code only detects images that have been saved with alpha channel. Images with an alpha channel may still be fully opaque (i.e. alpha = 1 for all pixels).

like image 152
Joni Avatar answered Oct 11 '22 03:10

Joni