overlay images in java

吃可爱长大的小学妹 提交于 2019-12-04 17:11:01
trashgod

I need to edit my images to get transparent background?

To make a particular color transparent, you can iterate through the pixels of a BufferedImage or use a suitable LookupOp. For the latter, see the articles cited here. You can then combine the images using drawImage(). The default composite rule, AlphaComposite.SRC_OVER, should be satisfactory; if not, you can change it, as shown here.

Your code should be fine for combining two images together. However, like you said, your two images are of the same size, and they do not seem to have any transparency. This will cause whatever image is drawn second to always "overwrite" the first image in the newly-combined image.

The solution you probably want for this, is to break the various pieces you want to overlay on top of each other out into separate, smaller images. With your images, it looks like you want to have various overlays on top of a tooth to display various pieces of information. You'll want to have three things in this case: an image of a tooth, an image containing the red overlay, and an image containing the blue overlay. All three of these images should have a transparent, and not white, background so that they don't overwrite colors in any previously-drawn image. When you do this, you'll want to draw the tooth, then overlay 1 (red/blue) then overlay 2 (red/blue). This should get you the output you're looking for.

The key is to set the alpha to float value, say two layer, set alpha to 0.5, three layer, set alpha 0.33, four layer, set alpha 0.25 ... Anyway, here is the code example

try
{
    BufferedImage imgA = ImageIO.read(new File(imgAPath, token));
    BufferedImage imgB = ImageIO.read(new File(imgBPath, token));

    if (imgA.getWidth() == imgB.getWidth() && imgA.getHeight() == imgB.getHeight()) 
    {
        float alpha = 0.5f;
        int compositeRule = AlphaComposite.SRC_OVER;
        AlphaComposite ac;
        int imgW = imgA.getWidth();
        int imgH = imgA.getHeight();
        BufferedImage overlay = new BufferedImage(imgW, imgH, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = overlay.createGraphics();
        ac = AlphaComposite.getInstance(compositeRule, alpha);
        g.drawImage(imgA,0,0,null);
        g.setComposite(ac);
        g.drawImage(imgB,0,0,null);
        g.setComposite(ac);
        ImageIO.write(overlay, "PNG", new File(logFolder, browser+"__"+token));
        g.dispose();
    }
    else
    {
        System.err.println(token+" dymension not match ");
    }
}
catch (IOException e)
{
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!