HomePHP Page 4 - An Image is Worth a Thousand Words in PHP Continued
Converting An Image - 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.
Now it's time to take a look at the meat of our application: the conversion process. It's a lot of code at first glance, but we'll break it into smaller sections. First, let's add the function to our class:
function get_image() { $text_image = NULL; $switch = FALSE;
# init image, if not already setup if ( !isset( $this->img_obj ) ) if ( !$this->init_img() ) return NULL;
// retrieve current pixel color info $rgb_color = imagecolorat( $this->img_obj, $x, $y ); $rgb_color = imagecolorsforindex( $this->img_obj, $rgb_color ); $red += $rgb_color['red']; $green += $rgb_color['green']; $blue += $rgb_color['blue'];
# average colors and output a block if ( $y % $this->skip_factor == $this->skip_factor - 1 && $x % $this->skip_factor == $this->skip_factor - 1 ) { $red /= $this->skip_factor; $green /= $this->skip_factor; $blue /= $this->skip_factor;
# if monochrome - the 'color' is actually the char, (the real color is always white if ( $this->return_format == 'MONOCHROME' ) { $hex_color = 'FFFFFF'; $char = $this->rgb_2_monochrome( $red, $green, $blue );
# if matrix mode, get a green color and a special char } else if ( $this->return_format == 'MATRIX' ) { $hex_color = $this->rgb_2_matrix( $red, $green, $blue ); $char = $this->get_matrix_char();
The above code can be split into four main sections: checking to make sure our image has been set up properly, walking through the image and retrieving color information, converting the information we have retrieved into colored text, and finally, returning the text we have created, complete with browser-specific CSS code, to be displayed.
The first step is rather easy. If an image has not been set up correctly, our function will return a NULL string, indicating failure.
Next our code enters a series of for loops. The outer loop walks through each pixel on the Y axis, and the inner walks through each pixel on the X axis. Using these loops, our function traverses each pixel of the specified image and collects information about the color of each pixel. This information is temporarily stored in loop variables 'red', 'green', and 'blue' and averaged every 'skip_factor' number of times through the loop. Once each skip factor is reached, and the colors have been averaged, our function checks for the user specified return format and uses our helper color and character functions in order to append the appropriate character to our return string.
Finally, once our function has completed its conversion loops, it calls out to 'get_css' to retrieve the appropriate browser-specific styling information. Without this information our image would still be recognizable, but not as pretty. And that's it.