Set BufferedImage alpha mask in Java

后端 未结 5 588
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 played recently a bit with this stuff, to display an image over another one, and to fade an image to gray.
    Also masking an image with a mask with transparency (my previous version of this message!).

    I took my little test program and tweaked it a bit to get the wanted result.

    Here are the relevant bits:

    TestMask() throws IOException
    {
        m_images = new BufferedImage[3];
        m_images[0] = ImageIO.read(new File("E:/Documents/images/map.png"));
        m_images[1] = ImageIO.read(new File("E:/Documents/images/mapMask3.png"));
        Image transpImg = TransformGrayToTransparency(m_images[1]);
        m_images[2] = ApplyTransparency(m_images[0], transpImg);
    }
    
    private Image TransformGrayToTransparency(BufferedImage image)
    {
        ImageFilter filter = new RGBImageFilter()
        {
            public final int filterRGB(int x, int y, int rgb)
            {
                return (rgb << 8) & 0xFF000000;
            }
        };
    
        ImageProducer ip = new FilteredImageSource(image.getSource(), filter);
        return Toolkit.getDefaultToolkit().createImage(ip);
    }
    
    private BufferedImage ApplyTransparency(BufferedImage image, Image mask)
    {
        BufferedImage dest = new BufferedImage(
                image.getWidth(), image.getHeight(),
                BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2 = dest.createGraphics();
        g2.drawImage(image, 0, 0, null);
        AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.DST_IN, 1.0F);
        g2.setComposite(ac);
        g2.drawImage(mask, 0, 0, null);
        g2.dispose();
        return dest;
    }
    

    The remainder just display the images in a little Swing panel.
    Note that the mask image is gray levels, black becoming full transparency, white becoming full opaque.

    Although you have resolved your problem, I though I could share my take on it. It uses a slightly more Java-ish method, using standard classes to process/filter images.
    Actually, my method uses a bit more memory (making an additional image) and I am not sure it is faster (measuring respective performances could be interesting), but it is slightly more abstract.
    At least, you have choice! :-)

提交回复
热议问题