How does image transparency work and how do I implement it?

感情迁移 提交于 2020-01-06 01:45:14

问题


I'm planning to make a colored overlay to put over a map of my city. However I want the overlay to only be semitransparent.

I know about rgba values and how the a value is what determines the transparency, but when working with the BufferedImage class, I can only assign one color to one pixel. Lets say you're given two images of the same size. How would I go about overlaying one over the other with the overlay having only half the opacity as the original image.


回答1:


Modify the alpha channel like this (opacity is from 0 to 255):

BufferedImage changeOpacity(BufferedImage img, int opacity) {
    final BufferedImage ret = new BufferedImage(img.getWidth(),
                                                img.getHeight(),
                                                BufferedImage.TYPE_INT_ARGB);
    final RescaleOp ro = new RescaleOp(new float[] {1f, 1f, 1f, ((float)opacity)/255f},
                                       new float[] {0f, 0f, 0f, 0f},
                                       null);
    ro.filter(img, ret);
    return ret;
}

Then overlay two images with alpha channels like this:

BufferedImage overlay(BufferedImage img1, BufferedImage img2) {
    final BufferedImage combined = new BufferedImage(img1.getWidth(),
                                                     img1.getHeight(),
                                                     BufferedImage.TYPE_INT_ARGB);
    final Graphics g = combined.getGraphics();
    g.drawImage(img1, 0, 0, null);
    g.drawImage(img2, 0, 0, null);
    return combined;
}


来源:https://stackoverflow.com/questions/32683202/how-does-image-transparency-work-and-how-do-i-implement-it

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!