I’m trying to create a method that converts a given java.awt.Color color to grayscale. Here’s what I have right now:
public Color gs(Color col) { if (grayScale) { float[] rgb = col.getRGBColorComponents(new float[3]); rgb[0] = rgb[1] = rgb[2] = (int)(0.299 * rgb[0] + 0.587 * rgb[1] + 0.114 * rgb[2]); col = new Color(rgb[0], rgb[1], rgb[2]); } return col; }
However, when I call this method, it seems to be returning the color black every single time, regardless of the input color. How do I fix this?
Advertisement
Answer
The float
components are in the range of [0.0, 1.0]
. You are adding the scaled RGB components together and then casting them to int
:
rgb[0] = rgb[1] = rgb[2] = (int)(0.299 * rgb[0] + 0.587 * rgb[1] + 0.114 * rgb[2]); ^^^ Cast to int
You would get the color black if all of the values in the rgb
array are zero. This is most likely because the cast to int truncates the resulting floating-point values down to zero. Since rgb
is an array of floats, you should cast result to float
.
rgb[0] = rgb[1] = rgb[2] = (float)(0.299 * rgb[0] + 0.587 * rgb[1] + 0.114 * rgb[2]); ^ Key change, cast to float