An Image is Worth a Thousand Words in PHP Continued - Final Preparation (
Page 3 of 5 )
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:
function init_img() {
$this->image_name = end( explode( '/', $this->image_path ) );
# determine type of file, and create it
switch( end( explode( '.', $this->image_name ) ) ) {
case 'jpg':
case 'jpeg': $this->img_obj = @ imagecreatefromjpeg( $this-
>image_path ); break;
case 'png': $this->img_obj = @ imagecreatefrompng( $this-
>image_path ); break;
case 'gif': $this->img_obj = @ imagecreatefromgif( $this-
>image_path ); break;
case 'bmp': $this->img_obj = @ imagecreatefromwbmp( $this-
>image_path ); break;
}
$this->image_width = @ imagesx( $this->img_obj );
$this->image_height = @ imagesy( $this->img_obj );
# return TRUE / FALSE to indicate success
return ( $this->img_obj != '' );
} # END init_img()
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.