【问题标题】:Layer multiple BufferedImages on top of one another?将多个 BufferedImage 层叠在一起?
【发布时间】:2012-06-21 23:51:16
【问题描述】:

我有多个透明的 BufferedImage 实例,我想将它们叠加在一起(也称为 Photoshop 层)并烘焙到一个 BufferedImage 输出中。我该怎么做?

【问题讨论】:

    标签: java bufferedimage


    【解决方案1】:

    我会说最好的办法是获取缓冲图像,并创建一个额外的图像以便附加一个对象。然后只需使用 Graphics.drawImage() 将它们放在一起。

    所以大致如下:

    BufferedImage a = ImageIO.read(new File(filePath, "a.png"));
    BufferedImage b = ImageIO.read(new File(filePath, "b.png"));
    BufferedImage c = new BufferedImage(a.getWidth(), a.getHeight(), BufferedImage.TYPE_INT_ARGB);
    
    Graphics g = c.getGraphics();
    g.drawImage(a, 0, 0, null);
    g.drawImage(b, 0, 0, null);
    

    【讨论】:

    • 我没有找到Graphics#draw 方法。我用Graphics#drawImage
    • 哇!我不敢相信你是这么久以来第一个指出这一点的人。我会更新答案,以免导致其他人误入歧途。
    【解决方案2】:

    假设第一个 BufferedImage 命名为 bi1,第二个命名为 bi2,而您要将它们分层的图像是目标。

    BufferedImage target=new BufferedImage(width,height,BufferedImage.TYPE_INT_ARGB);
    Graphics2D targetGraphics=target.createImage();
    targetGraphics.drawImage(bi1,0,0,null);//draws the first image onto it
    
    int[] pixels2=((DataBufferInt) bi2.getRaster().getDataBuffer()).getData();
    int[] pixelsTgt=((DataBufferInt) target.getRaster().getDataBuffer()).getData();
    for(int a=0;a<pixels2.length;a++)
    {
         pixelsTgt[a]+=pixels2[a];//this adds the pixels together
    }
    

    确保所有三个 BufferedImage 对象都是 TYPE_INT_ARGB 以便开启 alpha。如果两者加在一起大于最大整数,这可能无法为您提供您想要的确切结果,因此您可能需要添加一些东西来帮助解决这个问题。像素使用位移来添加颜色,其整数排序为 AARRGGBB。

    【讨论】:

      【解决方案3】:

      还要考虑可用于图形上下文的AlphaComposite 模式,讨论过here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-14
        • 1970-01-01
        • 2022-08-12
        • 1970-01-01
        • 2011-03-31
        • 2015-06-23
        相关资源
        最近更新 更多