HomePHP Page 2 - An Image is Worth a Thousand Words in PHP Continued
Examining the Code - PHP
Picking up where we left off in part one, we will work on some more helper methods and our conversion method. By the time we are done, we will have a fully functional image to text converter.
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).