skip to Main Content

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.

2

Answers


  1. Within Photoshop, you can use something called Actions. This can get you started. Since every PNG file’s primary layer is called Layer 0, this should work for every file. Record an action where you set the Layer Style of Layer 0 to be colored black. Then save the file and stop recording the Action. Use File >> Automate >> Batch to perform this on many files. I’d recommend saving a backup of the files in case you make a mistake.

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search