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

  1. Start with One opaque red pixel
  2. Do this Read its red channel
  3. Result 255
An eight-bit channel can store values from zero to 255.

Apply it to a real problem

  1. Start with Image pixel FF336699
  2. Do this Extract alpha, red, green and blue
  3. Result 255, 51, 102, 153
A thumbnail editor can inspect the four channels separately.
Advertisements

Run the example

Save as Main.java and run java Main.java with JDK 21.

Main.java
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);
    }
}
Output
255 51 102 153

Official Java documentation