The PNG Guide is an eBook based on Greg Roelofs' book, originally published by O'Reilly.



Compositing and Displaying the Image

What one does at this point is, of course, entirely application-specific. Our main program calls a display routine that simply puts the pixels on the screen, first compositing against the desired background color if the final image has four channels (i.e., if it includes an alpha channel). Then it waits for the user to quit the program, at which point it destroys the window, frees any allocated memory, and exits.

The compositing step is perhaps interesting; it employs a macro copied from the png.h header file, albeit renamed to avoid problems, should png.h ever be included in the main program file, and using equivalent typedefs:

#define alpha_composite(composite, fg, alpha, bg) {              \
    ush temp = ((ush)(fg)*(ush)(alpha) +                         \
                (ush)(bg)*(ush)(255 - (ush)(alpha)) + (ush)128); \
    (composite) = (uch)((temp + (temp >> 8)) >> 8);              \
}

The unique thing about this macro is that it does exact alpha blending on 8-bit samples (for example, the red components of a foreground pixel and a background pixel) without performing any division. This macro and its 16-bit-per-sample sibling have been tested on a number of PC and workstation architectures and found to be anywhere from 2 to 13 times faster than the standard approach, which divides by 255 or 65,535, depending on sample size. Of course, hardware-assisted alpha compositing will always be faster than doing it in software; many 3D accelerator cards provide this function, and often they can be used even in 2D applications. Approximate methods (which divide by 256 of 65,536 by bit-shifting) are another fast alternative when absolute accuracy is not important, but note that such an approach may leave a visible border between opaque and slightly transparent regions.




Last Update: 2010-Nov-26