Search code examples
javabufferedimage

How to programmatically remove background of an image in java?


Using bufferedImage or something is there a quick way to do this?

At present my approach:

All the images are centered on a white background. So the top left pixel is always white.

  • Start at the top left pixel, make it transparent.
  • From this pixel, see if any of the bordering pixels are white, if there are, make it transparent. For each of the bordering pixels that were white, check that pixels bordering pixels, and repeat for all connected pixels.

This seems ok to me. But I was wondering if there is a better way to do this?


Solution

  • But I was wondering if there is a better way to do this?

    AFAIK, no. (In fact, I suspect that it is provable that there is no alternative to your general approach.)

    However, your "repeat for all connected pixels" doesn't specify how you do that. The obvious alternatives are:

    • Recursive depth first - this is probably a bad idea, because there is a risk that you will overflow your call stack.
    • Breadth first using a queue of pixel positions for white pixels that are yet to be processed. This will process the pixels in a wave, and the maximum queue length will be the maximum wave "width".

    There may be other strategies.

    This problem is similar to flood filling, and flood-fill algorithms can be adapted to do this. Look at Best way to fill shapes in Java (no recursion) for some examples.