0

I have tried to make method which changes one color of BufferedImage to be invisible.
I can't find solution myself so I ask for your help.
Here is method made by me:

public static BufferedImage makeWithoutColor(BufferedImage img, Color col)
{
    BufferedImage img1 = img;
    BufferedImage img2 = new BufferedImage(img1.getWidth(), img1.getHeight(), BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = img2.createGraphics();
    g.setComposite(AlphaComposite.Src);
    g.drawImage(img1, null, 0, 0);
    g.dispose();
    for(int i = 0; i < img2.getWidth(); i++)
    {
        for(int j = 0; i < img2.getHeight(); i++)
        {
            if(img2.getRGB(i, j) == col.getRGB())
            {
                img2.setRGB(i, j, 0x8F1C1C);
            }
        }
    }
    return img2;
}

And here is one from tutorial i read.

public static BufferedImage makeColorTransparent(BufferedImage ref, Color color) {
    BufferedImage image = ref;
    BufferedImage dimg = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = dimg.createGraphics();
    g.setComposite(AlphaComposite.Src);
    g.drawImage(image, null, 0, 0);
    g.dispose();
    for(int i = 0; i < dimg.getHeight(); i++) {
        for(int j = 0; j < dimg.getWidth(); j++) {
            if(dimg.getRGB(j, i) == color.getRGB()) {
            dimg.setRGB(j, i, 0x8F1C1C);
            }
        }
    }
    return dimg;
}
Boblob
  • 109
  • 2
  • 2
  • 8

2 Answers2

2

Your mistake is this line:

for(int j = 0; i < img2.getHeight(); i++)

should be:

for(int j = 0; j < img2.getHeight(); j++)
//             ^                     ^ as Ted mentioned...
MByD
  • 135,866
  • 28
  • 264
  • 277
0

I assume that by "invisible" you mean that you want to make one color transparent. You aren't going to be able to do it using this approach, because setRGB doesn't affect the alpha channel. You are better off using an image filter. Here's an approach taken from this thread:

public static Image makeWithoutColor(BufferedImage img, Color col)
{
    ImageFilter filter = new RGBImageFilter() {

        // the color we are looking for... Alpha bits are set to opaque
        public int markerRGB = col.getRGB() | 0xFF000000;

        public final int filterRGB(int x, int y, int rgb) {
            if ((rgb | 0xFF000000) == markerRGB) {
                // Mark the alpha bits as zero - transparent
                return 0x00FFFFFF & rgb;
            } else {
                // nothing to do
                return rgb;
            }
        }
    };
    ImageProducer ip = new FilteredImageSource(im.getSource(), filter);
    return Toolkit.getDefaultToolkit().createImage(ip);
}

This will turn any pixel with the indicated RGB color and any transparency to a fully transparent pixel of the same color.

Community
  • 1
  • 1
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521