简体   繁体   中英

BufferedImage Color Channel Mask

I have found this code on JavaDoc, but I can't seem to understand it.

output.setRGB(x, y, (image.getRGB(x, y) & 0xff00ff00)
                    | ((image.getRGB(x, y) & 0xff0000) >> 16)
                    | ((image.getRGB(x, y) & 0xff) << 16));

All I know that this code turns blue color to red in a BufferedImage. but what if I want to replace blue with white or some other color and vice-versa?

I would appreciate any help.

Colors are stored like this, in hexadecimal:

RRGGBBAA

Red, green, blue, alpha. Now let's take a look at one of the lines:

(image.getRGB(x, y) & 0xff0000) >> 16

image.getRGB(x, y) would return an RRGGBBAA value, and this line is bitmasking it with 0xff0000 . Here is a visual:

RRGGBBAA
&
00FF0000
=
00GG0000

Therefore, it transforms the RRGGBBAA value into GG0000 .

Then, there is a bitshift 16 binary bits to the right. Java can't shift bits in hexadecimal, but we are visualizing the colors in hexadecimal right now. Therefore, we must convert the 16 binary shifts into 4 hex shifts, because hexadecimal is base-16. Binary is base-2, and 2^4 is 16, the base of hexadecimal.

Therefore, you must shift right 4 bits. This would turn GG0000 into GG , since the bits are being shifted 4 places to the right.

Therefore, we now have the value for the amount of green in our color.

You can apply similar logic to the other lines to see how they work.

When I work with color I use different idea:

    BufferedImage image = //create Buffered image
    int rgb = image.getRGB(x,y);   //get Rgb color value
    Color color = new Color(rgb);  // create color with this value
    Color resultColor = new Color(color.getRed(), color.getBlue(), color.getGreen()); //create new color change blue and green colors values
    image.setRGB(x,y,resultColor.getRGB());   //set color

I think this idea is easier to understand.

if you want to get white color use this :

    BufferedImage image = new BufferedImage();
    Color color = new Color(255,255,255);
    image.setRGB(x,y,color.getRGB());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM