Set BufferedImage alpha mask in Java

后端 未结 5 580
Happy的楠姐
Happy的楠姐 2020-11-29 02:50

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,

5条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-29 02:52

    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);
    }
    

提交回复
热议问题