HomePHP Page 3 - An Image is Worth a Thousand Words in PHP Continued
Final Preparation - 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're almost there! Just a few last knots to tie before we implement our conversion function. Let's go ahead and add in the rest of our class variables:
# number of pixels (X-axis) to average together to determine a color var $skip_factor = 5;
# store user-specified image information var $image_path = NULL; var $image_name = NULL; var $image_type = NULL;
# store pointer to PHP image object var $img_obj = NULL;
# store image dimensions var $image_width = 0; var $image_height = 0;
The above variables and comments are fairly self-explanatory, with the exception of 'skip_factor'. This variable simply specifies the number of pixels (along the X axis) we will be averaging in order to determine the color for each individual text character our class returns. The default value of 5 means that we will take the average value of every '5' pixels, and return exactly one text character. (Although this value is configurable, it should remain '5' for our application as changing it would require the CSS to be modified as well.)
Next, let's add a method that allows our user to specify the location of the image file they wish to convert. (Remember, this can be a local or remote image - so long as a valid path has been provided.)
# new load function - returns TRUE or FALSE to indicate success function load_image( $image_path ) { $this->image_path = $image_path; return ( $this->init_img() != FALSE ); } # END load_image()
And now for the last bit of preparation before we dive head-first into the conversion function:
The init() function, as you can see, simply checks the file extension of the user-specified image, and opens an image object for the appropriate file-type. It also stores the image dimensions within the class variables 'image_width' and 'image_height'.
Both functions will return TRUE upon success or FALSE upon failure. If FALSE is returned, the user either specified an invalid image path, or an unsupported input format.