javagraphicsalphacompositing

Set BufferedImage alpha mask in Java


I have two BufferedImages I loaded in from pngs. The first contains an image, the second an alpha mask for the image.

I want to create a combined image from the two, by applying the alpha mask. My google-fu fails me.

I know how to load/save the images, I just need the bit where I go from two BufferedImages to one BufferedImage with the right alpha channel.


Solution

  • Your solution could be improved by fetching the RGB data more than one pixel at a time(see http://java.sun.com/javase/6/docs/api/java/awt/image/BufferedImage.html), and by not creating three Color objects on every iteration of the inner loop.

    final int width = image.getWidth();
    int[] imgData = new int[width];
    int[] maskData = new int[width];
    
    for (int y = 0; y < image.getHeight(); y++) {
        // fetch a line of data from each image
        image.getRGB(0, y, width, 1, imgData, 0, 1);
        mask.getRGB(0, y, width, 1, maskData, 0, 1);
        // apply the mask
        for (int x = 0; x < width; x++) {
            int color = imgData[x] & 0x00FFFFFF; // mask away any alpha present
            int maskColor = (maskData[x] & 0x00FF0000) << 8; // shift red into alpha bits
            color |= maskColor;
            imgData[x] = color;
        }
        // replace the data
        image.setRGB(0, y, width, 1, imgData, 0, 1);
    }