Implementing Raster Operations using SVG Filter Elements

There is a rich legacy of raster-based image file formats in the world today that contain raster operations.  Given that each pixel's colour is represented by three 8-bit values representing red, green, and blue, these operations ignore the actual intensity values and instead combine individual bits of the representations using boolean arithmetic.  The inputs to these operations are typically the current brush or pen colour and the background.  One useful operation is XOR which inverts the background colour wherever a white object is drawn over it.  For example, 0xFF69B4 (hot pink) XOR 0xFFFFFF equals 0x00964B (forest green).  

Microsoft's Metafile formats, WMF and EMF, take raster operations to the extreme by offering all the possible boolean combinations of input values.  Very few of these are actually useful, but many can create some very artisitic effects.  We were given the job to build a Metafile to SVG converter, and needed to somehow  implement these arbitrary raster operations despite the fact that anything that manipulates individual pixel values doesn't fit in with vector-based SVG.  The first idea was to implement a lookup table using the feComponentTransfer filter primitive with type=discrete.  The two input values could somehow be combined to form the "index" into such a table.  Unfortunately, as there are 256 possible values for each input, such a table would be very unwieldy with (256x256) 65536 entries.  However, we discovered that if we use the four high-order bits of each eight-bit input value and combine these quantized values with raster operations, the results look very close to the original.  This meant that we could use a 256-element lookup table and the solution becomes realistic.  The input to the lookup table is formed by combining two quantized input values into one with a simple i + j>>4 operation.

The final algorithm takes the following steps for a two-input raster operation involving the background and the current brush or pen:
1. Confine the filter's effect to the area occupied by the source graphic;
2. Undo the gamma correction for the background image;
3. Quantizes the background colour values to multiples of 16/255 to effectively remove the low-order 4 bits;
4. Undo the gamma correction for the source graphic;
5. Quantize the source graphic colour values to multiples of 16/255 to effectively remove the low-order 4 bits;
6. Do the equivalent of i + j>>4 for the quantized background and source graphic components;
7. Use i + j>>4 as the input to a 256-entry ROP look-up table;
8. Redo the gamma correction. 

Expanding this algorithm for three-input raster operations that include a source bitmap image was relatively straightforward.
The presentation and paper proposed by this abstract includes more details and many colourful examples plus some later improvements to fidelity.