Java – Combine multiple images into a single image for later painting, with alpha blending


I have a graphics system for Java which allows objects to be "wallpapered" by specifying multiple images, which can have (relatively) complex alignment and resizing options applied.

In order to perform adequately (esp. on very low powered devices), I do the image painting to an internal image when the wallpaper is first painted, and then copy that composite image to the target graphics context to get it onto the screen. The composite is then recreated only if the object is resized so the only work for subsequent repaints is to copy the clipped region from the composite to the target graphics context.

The solution works really well, except that when I have PNG images with alpha-channel transparency the alpha channel is lost when painting the composite – that is the composite has all pixels completely opaque. So the subsequent copy to the on-screen graphics context fails to allow what's behind the wallpapered object show through.

I did manage to use an RGBImageFilter to filter out completely transparent pixels, but I can't see a solution with that to making blended transparency work.

Does anyone know of a way I can paint the images with the alpha-channel intact, and combined if two pixels with alpha values overlap?

Best Solution

What type of Image do you use for the composite image?

You should use a BufferedImage and set it's type to TYPE_INT_ARGB which allows translucency.

Related Question