Read the channels of a pixel in Java
Store a pixel in a small in-memory image. Extract each eight-bit color channel from its packed value, including the alpha channel.
A simple example
Read its red channel
- Start with One opaque red pixel
- Do this Read its red channel
- Result 255
Apply it to a real problem
- Start with Image pixel FF336699
- Do this Extract alpha, red, green and blue
- Result 255, 51, 102, 153
Advertisements
Run the example
Save as Main.java and run java Main.java with JDK 21.
import java.awt.image.BufferedImage;
public class Main {
public static void main(String[] args) throws Exception {
var image = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
image.setRGB(0, 0, 0xFF336699);
int pixel = image.getRGB(0, 0);
System.out.printf("%d %d %d %d%n", pixel >>> 24, (pixel >>> 16) & 255,
(pixel >>> 8) & 255, pixel & 255);
}
}
255 51 102 153