An Image is Worth a Thousand Words in PHP Continued - Examining the Code (
Page 2 of 5 )
We've just added a lot of code at once, but each method is pretty straight-forward. First we have our 'init' methods: init_hex_array and init_monochrome_array. These methods simply make sure that our 'HEX' (hexadecimal) and 'monochrome' value arrays have been created and indexed properly. The monochrome array is probably pretty straightforward, but the HEX array may be a little more confusing. Basically, we start by specifying a string of all possible HEX values, in ascending order (0-9, A-F). Our 'init' function simply iterates through that list and expands it to a two-character representation (00 through FF).
Next we have our various conversion methods, rgb_2_*. Each of these methods is highly specified, and takes a series of arguments specifying the red, green, and blue color values for a given image pixel. Each function then uses the helper, 'rgb_2_hex' function to convert the various pieces of color data into an appropriate return format.
The color function then simply converts the RGB value to a direct HEX equivalent (0,0,0 = 000000 and 255, 255, 255 = FFFFFF). Next, our grayscale function averages the three color values together, and returns a HEX string representing that average. (This is because a grayscale image is comprised of an equal amount of red, green, and blue, with a varying brightness or intensity). Next, our matrix conversion function averages the RGB values, and then returns a modified HEX string including only green values (000000 through 00FF00). (Similar to our grayscale function, a matrix image is made up of all green colors, so our function simply discards any red or blue color information and averages in the brightness of all three values).
Finally, our monochrome conversion function doesn't return a color at all; it returns a character. Why is this? Because a monochrome image consists of only two colors - in our case, white and black (white characters on a black background). So rather than return a color, the 'rgb_2_monochrome' function determines the brightness of the pixel (by averaging the three colors present) and then returns a character of text that represents that approximate brightness level. For our example application, we have specified the characters ' .:xW©'. As you may be able to tell, each character is slightly heavier than the character before it. In our application this will result in a very cool, 'monochrome' effect - but we'll see that shortly.