Set BufferedImage alpha mask in Java

后端 未结 5 586
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 03:02

    I'm too late with this answer, but maybe it is of use for someone anyway. This is a simpler and more efficient version of Michael Myers' method:

    public void applyGrayscaleMaskToAlpha(BufferedImage image, BufferedImage mask)
    {
        int width = image.getWidth();
        int height = image.getHeight();
    
        int[] imagePixels = image.getRGB(0, 0, width, height, null, 0, width);
        int[] maskPixels = mask.getRGB(0, 0, width, height, null, 0, width);
    
        for (int i = 0; i < imagePixels.length; i++)
        {
            int color = imagePixels[i] & 0x00ffffff; // Mask preexisting alpha
            int alpha = maskPixels[i] << 24; // Shift blue to alpha
            imagePixels[i] = color | alpha;
        }
    
        image.setRGB(0, 0, width, height, imagePixels, 0, width);
    }
    

    It reads all the pixels into an array at the beginning, thus requiring only one for-loop. Also, it directly shifts the blue byte to the alpha (of the mask color), instead of first masking the red byte and then shifting it.

    Like the other methods, it assumes both images have the same dimensions.

提交回复
热议问题