Java – How do I XOR the pixel values of two bitmaps together?

How do I XOR the pixel values of two bitmaps together?… here is a solution to the problem.

How do I XOR the pixel values of two bitmaps together?

I

have some bitmap A and I modify it to generate bitmap B. I want to efficiently generate bitmap D by XOR the pixel values of A and B together, so that D XOR A generates bitmap B AND D XOR B GENERATES BITMAP A. I want to store the differences between bitmaps so I can undo the changes made.

So far I’ve tried :

  1. Draw A onto B using a drawing object I call .setXfermode (new PorterDuffXfermode(PorterDuff.Mode.XOR)). This applies when alphas for A and B are 255 everywhere, but below any value produces poor results. For example, if I XOR A to A, I expect the result to be a blank image. With this xfer pattern, most of A will disappear, but the part without full alpha will remain.

  2. Draw A to B using the drawing object I have called .setXfermode(new PixelXorXfermode(0)). This xfer pattern breaks the alpha value, which is not what I want. I’m also not sure what useful things I can set the constructor value to.

What can I do? I need to treat pixel values as normal values and not something that treats alpha values as exceptions. I need it to be fairly fast (like the painting type above) and it would be too slow to use something like setpixel/getpixel or do calculations in byte[] myself.

EDIT: Can someone help? Even knowing that most people don’t believe there is an API call that can do this for me would help. I almost can’t wait to switch to OpenGL rendering because it has an XOR rendering mode (I hope it doesn’t have the same issues mentioned above).

Solution

Is it possible to try to XOR on the bitmap’s byte array before drawing? This does not provide special treatment for alpha and may theoretically work if the bitmaps are the same size. Probably not soon, of course….

Or you can use one of the above methods, but somehow manipulate the alpha values in the byte array and handle them separately?

Related Problems and Solutions