How to invert an RGB color in integer form?

2019-06-16 06:19发布

问题:

Given an RGB color in 32-bit unsigned integer form (eg. 0xFF00FF), how would you invert it (get a negative color), without extracting its individual components using bitshift operations?

I wonder whether it's possible using just bitwise operations (AND, OR, XOR).

More precisely, what's the algorithm that uses the least number of instructions?

回答1:

I think it is so simple. You can just calculate 0xFFFFFF-YourColor. It will be the inverted color.

int neg = 0xFFFFFF - originalRGB

// optional: set alpha to 255:
int neg = (0xFFFFFF - originalRGB) | 0xFF000000;


回答2:

Use this method to invert each color and maintain original alpha.

int invert(int color) {
  return color ^ 0x00ffffff;
}

xor (^) with 0 returns the original value unmodified. xor with 0xff flips the bits. so in the above case we have 0xaarrggbb we are flipping/inverting r, g and b.

This should be the most efficient way to invert a color. arithmetic is (marginally) slower than this utterly simple bit-wise manipulation.

if you want to ignore original alpha, and just make it opaque, you can overwrite the alpha:

int invert(int color) {
  0xff000000 | ~color;
}

in this case we just flip every bit of color to inverse every channel including alpha, and then overwrite the alpha channel to opaque by forcing the first 8 bits high with 0xff000000.



回答3:

You could simply perform the negation of the color. Snippet:

~ color


回答4:

Color color_original = Color.lightGray;

int rgb = color_original.getRGB();

int inverted = (0x00FFFFFF - (rgb | 0xFF000000)) | (rgb & 0xFF000000);

Color color_inverted = new Color(inverted);


回答5:

Your question is unclear; no colors in RGB are "negative colors".

You could invert an image, as though it was a film negative. Is that what you meant?

If you wanted to invert an image that has just one pixel of color 0xFF00FF, the calculation is to subtract from white, 0xFFFFFF.

> negative_result_color = 0xFFFFFF - 0xFF00FF
> negative_result_color == 0x00FF00
true

In a computer, a subtraction is done by adding the compliment: http://en.wikipedia.org/wiki/Method_of_complements#Binary_example

But seriously, why wouldn't you just let the machine do the subtraction for you with your ordinary code? Its what they're good at.