1

I have a BufferedImage and I am trying to fill a rectangle with transparent pixels. The problem is, instead of replacing the original pixels, the transparent pixels just go on top and do nothing. How can I get rid of the original pixel completely? The code works fine for any other opaque colors.

public static BufferedImage[] slice(BufferedImage img, int slices) {
    BufferedImage[] ret = new BufferedImage[slices];

    for (int i = 0; i < slices; i++) {
        ret[i] = copyImage(img);

        Graphics2D g2d = ret[i].createGraphics();

        g2d.setColor(new Color(255, 255, 255, 0));

        for(int j = i; j < img.getHeight(); j += slices)
            g2d.fill(new Rectangle(0, j, img.getWidth(), slices - 1));

        g2d.dispose();
    }

    return ret;
}

public static BufferedImage copyImage(BufferedImage source){
    BufferedImage b = new BufferedImage(source.getWidth(), source.getHeight(), BufferedImage.TYPE_INT_ARGB);
    Graphics g = b.getGraphics();
    g.drawImage(source, 0, 0, null);
    g.dispose();
    return b;
}
takra
  • 457
  • 5
  • 15
  • 2
    You have to set an appropriate `AlphaComposite`. I'm not sure whether there is an *exact* duplicate of this question, but have a look at http://stackoverflow.com/a/6297069/3182664 (Ignore the accepted answer there. The right approach is that using `AlphaComposite`, as in the answer that I linked to) – Marco13 May 10 '17 at 01:26
  • @Marco13 Thanks, that worked out great! Maybe post it as an answer so I can accept it? – takra May 10 '17 at 01:29
  • @minerguy31 You could self answer, as the answer isn't quite the accepted duplicate answer – MadProgrammer May 10 '17 at 01:32

1 Answers1

3

Using AlphaComposite, you have at least two options:

  1. Either, use AlphaComposite.CLEAR as suggested, and just fill a rectangle in any color, and the result will be a completely transparent rectangle:

    Graphics2D g = ...;
    g.setComposite(AlphaComposite.Clear);
    g.fillRect(x, y, w, h);
    
  2. Or, you can use AlphaComposite.SRC, and paint in a transparent (or semi-transparent if you like) color. This will replace whatever color/transparency that is at the destination, and the result will be a rectangle with exactly the color specified:

    Graphics2D g = ...;
    g.setComposite(AlphaComposite.Src);
    g.setColor(new Color(0x00000000, true);
    g.fillRect(x, y, w, h);
    

The first approach is probably faster and easier if you want to just erase what is at the destination. The second is more flexible, as it allows replacing areas with semi-transparency or even gradients or other images.


PS: (As Josh says in the linked answer) Don't forget to reset the composite after you're done, to the default AlphaComposite.SrcOver, if you plan to do more painting using the same Graphics2D object.

Harald K
  • 26,314
  • 7
  • 65
  • 111