Search code examples
javaimagecolorsgrayscale

Colorize a Grayscale Image in Java


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:

grayscale

to turn into this:

colored

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.


Solution

  • Miguel’s answer on the question to which you’ve linked provides the solution, albeit not directly as Java code:

    • Convert the grayscale value of each pixel in the original image into a brightness value in an HSB color for corresponding pixel in the converted image.
    • Keep the hue of each HSB color the same at all times; that’s the color you want to apply.
    • I found setting the saturation to 100% looked good, but you are free to try other saturation values.
    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);
            }
        }
    }