I'm making a program in Java that takes a grayscale image and assigns a random color to it, but I can't seem to find a way to make it work. I've looked at a couple of pages I found on the subject (this page and this page), but I can't really understand how those work.
Ideally, I want a grayscale image like this:
to turn into this:
I've tried using a hue changer, but it doesn't work on grayscale images. Everything else I've tried doesn't seem to work either.
Miguel’s answer on the question to which you’ve linked provides the solution, albeit not directly as Java code:
public static void colorize(BufferedImage image,
float hue) {
Objects.requireNonNull(image, "Image cannot be null.");
if (hue < 0 || hue > 1 || Float.isNaN(hue)) {
throw new IllegalArgumentException(
"Hue must be between 0 and 1 inclusive.");
}
int width = image.getWidth();
int height = image.getHeight();
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int argb = image.getRGB(x, y);
int alpha = (argb & 0xff000000);
int grayLevel = (argb >> 8) & 0xff;
float brightness = grayLevel / 255f;
int rgb = Color.HSBtoRGB(hue, 1, brightness);
argb = (rgb & 0x00ffffff) | alpha;
image.setRGB(x, y, argb);
}
}
}