javacolorsbufferedimagecolorize

Colorizing images in Java


I'm working on some code to colorize an image in Java. Basically what I'd like to do is something along the lines of GIMP's colorize command, so that if I have a BufferedImage and a Color, I can colorize the Image with the given color. Anyone got any ideas? My current best guess at doing something like this is to get the rgb value of each pixel in the BufferedImage and add the RGB value of the Color to it with some scaling factor.


Solution

  • I have never used GIMP's colorize command. However, if your getting the RGB value of each pixel and adding RGB value to it you should really use a LookupOp. Here is some code that I wrote to apply a BufferedImageOp to a BufferedImage.

    Using Nicks example from above heres how I would do it.

    Let Y = 0.3*R + 0.59*G + 0.11*B for each pixel

    (R1,G1,B1) is what you are colorizing with

    protected LookupOp createColorizeOp(short R1, short G1, short B1) {
        short[] alpha = new short[256];
        short[] red = new short[256];
        short[] green = new short[256];
        short[] blue = new short[256];
    
        int Y = 0.3*R + 0.59*G + 0.11*B
    
        for (short i = 0; i < 256; i++) {
            alpha[i] = i;
            red[i] = (R1 + i*.3)/2;
            green[i] = (G1 + i*.59)/2;
            blue[i] = (B1 + i*.11)/2;
        }
    
        short[][] data = new short[][] {
                red, green, blue, alpha
        };
    
        LookupTable lookupTable = new ShortLookupTable(0, data);
        return new LookupOp(lookupTable, null);
    }
    

    It creates a BufferedImageOp that will mask out each color if the mask boolean is true.

    Its simple to call too.

    BufferedImageOp colorizeFilter = createColorizeOp(R1, G1, B1);
    BufferedImage targetImage = colorizeFilter.filter(sourceImage, null);
    

    If this is not what your looking for I suggest you look more into BufferedImageOp's.

    This is would also be more efficient since you would not need to do the calculations multiple times on different images. Or do the calculations over again on different BufferedImages as long as the R1,G1,B1 values don't change.