改变java中透明像素的颜色

时间:2014-01-15 11:20:52

标签: java image-processing

现在我能够将另一个图像的像素应用到pg到m的源图像像素。但问题是我失去了渐变或褪色效果。

     public static void main(String[] args){
        try {
            BufferedImage image = ImageIO.read(new File("c:\\m.png"));
            BufferedImage patt = ImageIO.read(new File("c:\\pg.png"));

            int f = 0;
            int t = 0;
            int n = 0;
            BufferedImage bff = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);
            for (int y = 0; y < image.getHeight(); ++y) {
                for (int x = 0; x < image.getWidth(); ++x) {
                    int argb = image.getRGB(x, y);
                    int nrg = patt.getRGB(x, y);

                    if(((argb>>24) & 0xff) == 0) {
                                bff.setRGB(x, y, (255<<24));
                    } else {
                                bff.setRGB(x, y, nrg);
                    }                               
                }
            }
            System.out.println("Trans : " + t + " Normal : " + n);
            File outputfile = new File("c://imagetest.png");
            ImageIO.write(bff, "png", outputfile);
        } catch (IOException ex) {

        }

}

感谢。

2 个答案:

答案 0 :(得分:2)

0xff000000是不透明的黑色,0x00000000是完全透明的。

什么是0(您选择的颜色)?

是的,它是透明的。

尝试0xff000000甚至更好:argb ^ 0xff000000,只改变透明度。

                if(((argb>>24) & 0xff) == 0) {
                            bff.setRGB(x, y, argb ^ 0xff000000);
                } else {
                            bff.setRGB(x, y, argb);
                }                               

答案 1 :(得分:0)

对于BufferedImage.setRGB(int x, int y, int rgb)rgb值的组成如下:

11111111 11111111 11111111 11111111
Alpha    Red      Green    Blue

在您的代码中,您将测试以下内容:

if (((argb >> 24) & 0xff) == 0)

测试Alpha值为0,因此完全透明。

当您发现它为真时,然后使用

将rgb值设置为0
bff.setRGB(x, y, 0);

所以你再次将它设置为透明。

将其更改为

bff.setRGB(x, y, (255<<24));

bff.setRGB(x, y, 0xff000000); //This should be better

会将其更改为不透明的黑色像素。这将具有二进制值

  

11111111000000000000000000000000

编辑: Moritz Petersen's solution应该更好,因为它会保留像素的颜色,同时消除透明度。

如果您想将其设置为特定颜色,您可以这样做:

bff.setRGB(x, y, 0xffff0000); // red
bff.setRGB(x, y, 0xff00ff00); // green
bff.setRGB(x, y, 0xff0000ff); // blue

或红色,绿色和蓝色值的任意组合。

相关问题