Date: 2021jul15
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
import java.awt.Color;
import java.awt.image.BufferedImage;
void showColorsSlow(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:
void showColorsFast(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);
}
}
Using these helper functions:
byte getBlue(final int pixel) {
return (byte) (pixel & 0xff);
}
byte getGreen(final int pixel) {
return (byte) ((pixel >> 8) & 0xff);
}
byte getRed(final int pixel) {
return (byte) ((pixel >> 16) & 0xff);
}
byte getAlpha(final int pixel) {
return (byte) ((pixel >> 24) & 0xff);
}