Search code examples
javagraphicspngfilledge-detection

Fill complex image with color


Let's say I have a PNG image with transparency, like so: sword with transparent background

I want, in Java, to fill only the object with black, like so: sword filled with black

This is a fairly trivial process in Photoshop, but this is a process I'd like to repeat frequently, ideally without making a black fill picture for each object I'd like to do it for. I've tried several edge detecting classes but found no success.

How would I accomplish this?

Additional info: this is going to be a quick-and-dirty way to create shadows. If you can think of a better way, that would solve this problem completely.


Solution

  • You could make a function that loops through all the pixels and fill them with black color.

    BufferedImage image = ...
    Color fillColor = new Color(0, 0, 0); // Black
    
    for (int y = 0; y < image.getHeight(); y++) {
        for (int x = 0; x < image.getWidth(); x++) {
            int color = image.getRGB(x, y);
            int alpha = (color >> 24) & 0xff;
    
            if (alpha == 255) {
                image.setRGB(x, y, fillColor.getRGB());
            }
        }
    }
    

    Obviously, this will only work on fully opaque pixels. If the image on top contains some transparency, you can also change the condition to be more tolerant: if (alpha > 127). This will fill all pixels that are less than 50% transparent.