Programming Tips - Java: Get colors from BufferedImage

Date: 2021jul15 Update: 2025sep24 OS: non-Andr_id Language: Java Keywords: avoid new Color Q. Java: Get colors from BufferedImage A. Here is an example function that prints all the colors from the first row of an image as shown in this full example:
import java.awt.Color; import java.awt.image.BufferedImage; class Demo { // Helper functions static byte getBlue(final int pixel) { return (byte) (pixel & 0xff); } static byte getGreen(final int pixel) { return (byte) ((pixel >> 8) & 0xff); } static byte getRed(final int pixel) { return (byte) ((pixel >> 16) & 0xff); } static byte getAlpha(final int pixel) { return (byte) ((pixel >> 24) & 0xff); } static void showColorsSlow(final BufferedImage bitmap) { final int y = 0; Color color; int red, green, blue; for (int x = 0; x < bitmap.getWidth(); x++) { color = new Color(bitmap.getRGB(x, y)); red = color.getRed(); green = color.getGreen(); blue = color.getBlue(); System.out.println("red=" + red + " green=" + green + " blue=" + blue); } } // Notice it does a `new Color` for every pixel! // We can refactor the function to avoid the AWT Color class: static void showColorsFast(final BufferedImage bitmap) { final int y = 0; int pixel; byte red, green, blue; for (int x = 0; x < bitmap.getWidth(); x++) { pixel = bitmap.getRGB(x, y); red = getRed(pixel); green = getGreen(pixel); blue = getBlue(pixel); System.out.println("red=" + red + " green=" + green + " blue=" + blue); } } public static final void main(String []args) { BufferedImage bitmap = new BufferedImage(10, 10, BufferedImage.TYPE_INT_ARGB); showColorsFast(bitmap); } }