Discover how image filters work, how they can spice up your images, how to take advantage of them in PHP, and how to create custom filters that go far beyond the built-in filter effects.

WEBINAR:

On-Demand

Color Bitwise Operations
The right-shift (>>) and OR (|) bitwise operators play an important role in color representation. For example, as you probably know, a color can be represented by a 32-bit integer; each color component uses a specific number of bits—eight bits in the default color model (RGBA). The following example creates the pure red color A=255,R=255,G=0,B=0 by using the right-shift operator to set the bits for each color component and then using the OR operator to combine the color components to represent the final color.

For example, to form a pure red color, you set the color by shifting the alpha value (255) by 24 positions, the red value (255) by 16 positions, the green value (0) by 8 positions, and the blue value (0) by 0 positions:

You can also use the bit operators to extract the individual RGB values for a given color. In the following example, the imagecolorat function returns the color of a pixel, and the bit shift operations extract the individual RGB values:

Figure 4. The Green Band: After removing the red and blue bands of the tree.jpg picture, the image appears in shades of green.

In a larger version of the same technique you can extract the color bands of an entire image. The following code extracts the red, green and blue color bands by looping through each pixel, retrieving the color value for that pixel, and then extracting the various color components. The code to get and assign the red and blue bands is commented out, so the resulting image shows only the green band (see Figure 4):

Similarly, you can extract the red or blue bands by un-commenting the appropriate section of code in the preceding example.

Using the bitwise operators and playing around with pixel colors you can obtain great filters with only a few lines of code. To give you a sense of the possibilities, the rest of this article discusses and shows the code for many different filters, all of which are fairly simple to create and apply. Some of these filters alter color while some alter other properties such as brightness or contrast. Finally, you'll see some built-in filters that can perform embossing, edge-smoothing, and other filtering operations.