Java Image Transparency Detection BufferedImage
In this tutorial we demonstrate how to detect image transparency in java. The first method is to check if an image contains an alpha channel. In the second method we loop over each pixel and evaluate if the pixel is transparent.
Image Transparency Detection
We use the following images. The first is a PNG
image which contains transparent pixels and an alpha channel. The second is a JPG
image which does not contain transparency or an alpha channel.
duke.png | duke.jpg |
---|---|
Size: 9KB | Size: 11KB |
Java Image Transparency Detection BufferedImage
The following example demonstrates how to detect if an image contains a transparent pixel.
package com.memorynotfound.image;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class DetectImageTransparency {
public static void main(String... args) throws IOException {
File pngInput = new File("/tmp/duke.png");
BufferedImage pngImage = ImageIO.read(pngInput);
checkTransparency(pngImage);
File jpgInput = new File("/tmp/duke.jpg");
BufferedImage jpgImage = ImageIO.read(jpgInput);
checkTransparency(jpgImage);
}
private static void checkTransparency(BufferedImage image){
if (containsAlphaChannel(image)){
System.out.println("image contains alpha channel");
} else {
System.out.println("image does NOT contain alpha channel");
}
if (containsTransparency(image)){
System.out.println("image contains transparency");
} else {
System.out.println("Image does NOT contain transparency");
}
}
private static boolean containsAlphaChannel(BufferedImage image){
return image.getColorModel().hasAlpha();
}
private static boolean containsTransparency(BufferedImage image){
for (int i = 0; i < image.getHeight(); i++) {
for (int j = 0; j < image.getWidth(); j++) {
if (isTransparent(image, j, i)){
return true;
}
}
}
return false;
}
public static boolean isTransparent(BufferedImage image, int x, int y ) {
int pixel = image.getRGB(x,y);
return (pixel>>24) == 0x00;
}
}
Output:
image contains alpha channel
image contains transparency
image does NOT contain alpha channel
Image does NOT contain transparency