Location: PHPKode > scripts > array_to_image > array_to_image/array_to_image.php
<?php
//
// Class to render array as image
//

/**
*
* Class array_to_image: show a bidimensional array as an image representing
* a table. Allows:
* - set max image size and automatly resize if the resulting image is to big
* - different background and text color for head and rows
* - alternate background abd text color for even and odd rows
* - PNG or JPG format
* - store to files or show directly
*
* @author       Roberto 'Frank' Franchini <hide@address.com>
* @version      1.1
*
*/

class array_to_image
{
    /**
     * Array to be showed
     * @var  array
     * @access   public
     */
    var $arr;
    /**
     * Image handle
     * @var  handler
     * @access   private
     */
    var $image;     
    /**
     * Fonts and colors parameters
     * @var  font
     * @access   private
     */
    var $font;
    var $fontWidth;
    var $even_bgcolor;
    var $even_txt_color;
    var $odd_bgcolor;
    var $odd_txt_color;
    var $head_bgcolor;
    var $head_txt_color;
    var $line_color;
    //options
    var $cellspacing;
    var $center;  //if true center the text
    var $max_x;   //max dimension
    var $max_y;
    var $type;
    //private parameters (calculated)
    var $rows;  //number of rows and columns
    var $cols;
    var $dim_x; //width and height in pixel of the resulting image
    var $dim_y;
    var $row_height;  //height of each row in pixel
    //it's all OK?
    var $flag;

    //constructor
    function array_to_image($arr=array(), $font=2, $cellspacing=5,
                $center=true, $max_x=600, $max_y=600, $type='png',
                $line_color="0,0,0",
                $head_bgcolor="128,128,128", $head_txt_color="0,0,0",
                $even_bgcolor="230,230,230", $even_txt_color="0,0,0",
                $odd_bgcolor="214,214,214", $odd_txt_color="0,0,0")
    {
        $this->arr              = $arr;
        $this->font             = $font;
        $this->even_bgcolor     = $this->_setcolor($even_bgcolor);
        $this->even_txt_color   = $this->_setcolor($even_txt_color);
        $this->odd_bgcolor      = $this->_setcolor($odd_bgcolor);
        $this->odd_txt_color    = $this->_setcolor($odd_txt_color);
        $this->head_bgcolor     = $this->_setcolor($head_bgcolor);
        $this->head_txt_color   = $this->_setcolor($head_txt_color);
        $this->line_color       = $this->_setcolor($line_color);
        $this->cellspacing      = $cellspacing;
        $this->center           = $center;
        $this->max_x            = $max_x;
        $this->max_y            = $max_y;
        $this->type             = $type;
        $this->rows     = 0;
        $this->cols     = 0;
        $this->dim_x    = 0;
        $this->dim_y    = 0;
        $this->flag     = 1;
        $this->image    = 0;
    } //end constructor
    
    //destructor
    function _array_to_image() 
    {
        $this->arr              = null;
        $this->font             = null;
        $this->even_bgcolor     = null;
        $this->even_txt_color   = null;
        $this->odd_bgcolor      = null;
        $this->odd_txt_color    = null;
        $this->head_bgcolor     = null;
        $this->head_txt_color   = null;
        $this->line_color       = null;
        $this->cellspacing      = null;
        $this->center           = null;
        $this->max_x            = null;
        $this->max_y            = null;
        $this->type             = null;
        $this->rows     = 0;
        $this->cols     = 0;
        $this->dim_x    = 0;
        $this->dim_y    = 0;
        $this->flag     = 1;
    } //end constructor
    
    /**
     * Show or store to the given file name the image
     * in the selected format. It calls _image_create() if
     * the handle isn't setted, and then calls _draw_table()
     * that draws the table on the handle.
     *
     * @param   string  $name       name of file where to store the image
     * @param   bool    $destroy    tells if the image handle should be destoyed 
     * @access  public
     * @returns image               png or jpg image if $name is setted
    */
    function show_image($nome='', $destroy=true)
    {
        if (!$this->image) {
            $this->_create_image();
        }
        $this->_draw_table();
        switch ($this->type) {
        case 'png':
            if ($nome) {
                imagepng($this->image,$nome.".png");
            } else {
                header("Content-type: image/png");
                imagepng($this->image);
            }
            break;
        case 'jpeg':
            if ($nome) {
                imagejpeg ($this->image,$nome.".jpg");
            } else {
                header ("Content-type: image/jpeg");
                imagejpeg ($this->image);
            }
            break;
        }
        if ($destroy == true) {
            $this->_array_to_image();
            imagedestroy($this->image);
        }
    } //end func show_image

    /**
    * Create an associative array for color values
    * 
    * @param    sting   $color comma separated value for Red,Green,Blue
    * @access   private 
    * @returns  associative arrary of colors
    */
    function _setcolor($color)
    {
        $color  = explode(",",$color);
        $red    = $color[0];
        $green  = $color[1];
        $blue   = $color[2];
        return (array(red=>$red,green=>$green,blue=>$blue));
    }

    /**
    * Set colors for all types of cells
    * 
    * @access   private
    * @returns  none
    */
    function _set_cells_color()
    {
        //setto i colori
        $this->even_bgcolor     = imagecolorallocate($this->image, $this->even_bgcolor[red], $this->even_bgcolor[green], $this->even_bgcolor[blue] );
        $this->even_txt_color   = imagecolorallocate($this->image, $this->even_txt_color[red], $this->even_txt_color[green], $this->even_txt_color[blue] );
        $this->odd_bgcolor      = imagecolorallocate($this->image, $this->odd_bgcolor[red], $this->odd_bgcolor[green], $this->odd_bgcolor[blue] );
        $this->odd_txt_color    = imagecolorallocate($this->image, $this->odd_txt_color[red], $this->odd_txt_color[green], $this->odd_txt_color[blue] );
        $this->line_color       = imagecolorallocate($this->image, $this->line_color[red], $this->line_color[green], $this->line_color[blue] );
        $this->head_bgcolor     = imagecolorallocate($this->image, $this->head_bgcolor[red], $this->head_bgcolor[green], $this->head_bgcolor[blue] );
        $this->head_txt_color   = imagecolorallocate($this->image, $this->head_txt_color[red], $this->head_txt_color[green], $this->head_txt_color[blue] );
        $line_color             = imagecolorallocate($this->image, $this->line_color[red], $this->line_color[green], $this->line_color[blue] );
    } //end func _setcolor

    /**
    * Create the image and if necesary resize it to fit the 
    * max dimension required. This method only allocates graphic space
    * where to draw the table
    *
    * @access   private
    * @returns  none
    */

    function _create_image()
    {
        if ((!$this->cols) || (!$this->rows)) $this->_max_cells_width();
        if ((!$this->dim_x) || (!$this->dim_y)) $this->_image_dimension();
        //if calculated dimension of resulting image are bigger than
        // max dimension, drop down font dimension and cellspacing
        while (($this->dim_x > $this->max_x) or ($this->dim_y > $this->max_y) 
                and ($this->font > 1 or $this->cellspacing > 1 )) {
            $this->cellspacing = ($this->cellspacing > 1) ? $this->cellspacing-1 : 1;
            $this->font = ($this->font > 1) ? $this->font-1 : 1;
            $this->_max_cells_width();
            $this->_image_dimension();
        }
        //now i can create the image
        $this->image = imagecreate($this->dim_x, $this->dim_y);
        $this->_set_cells_color();
    } //end func _create_image

    /**
    * Draw the table as image. Doesn't show any output.
    * 
    * @access   private
    * @returns  none
    */
    
    function _draw_table()
    {
        $y2 = 0;
        $x2 = 0;
        reset($this->arr);
        $y1 = 0;
        $even = true;
        while (list($rowKey,$row) = each($this->arr) ) {
            $x1 = 0;
            if ($rowKey =='width') continue;
            /*'for' statement is necessary for draw cell's rectangle
            * on empty cells
            * This 'while' statement will not round empty cells:
            * while (list($colKey,$element) = each ($row)) {
            */
            for ($colKey = 0; $colKey < $this->cols ; $colKey++) {
                $element = $this->arr[$rowKey][$colKey];
                $col_width = $this->arr['width'][$colKey] * $this->fontWidth + 2*$this->cellspacing;
                $string = $element;
                if ($this->center) {
                    $str_width = strlen($string) * $this->fontWidth;
                    $shift = ($col_width - $str_width) / 2 - $this->cellspacing;
                }
                $x2 = $x1 + $col_width;
                $y2 = $y1 + $this->row_height;
                //if index point to table's head apply style
                if ($rowKey == 'head') {
                    imagefilledrectangle($this->image, $x1, $y1, $x2, $y2, $this->head_bgcolor);
                    ImageString($this->image, $this->font, $x1+$this->cellspacing+$shift, $y1+$this->cellspacing, $string, $this->head_txt_color);
                } elseif ($even) {
                    imagefilledrectangle($this->image, $x1, $y1, $x2, $y2, $this->even_bgcolor);
                    ImageString($this->image, $this->font, $x1+$this->cellspacing+$shift, $y1+$this->cellspacing, $string, $this->even_txt_color);
                } else {
                    imagefilledrectangle($this->image, $x1, $y1, $x2, $y2, $this->odd_bgcolor);
                    ImageString($this->image, $this->font, $x1+$this->cellspacing+$shift, $y1+$this->cellspacing, $string, $this->odd_txt_color);
                }
                imagerectangle($this->image, $x1, $y1, $x2, $y2, $this->line_color);
                $x1 = $x2; //next column 
            }
            $y1 = $y2; //next row
            $even = !$even;
        }
    } //end func _draw_table
    

    /**
     * Claculate the pixel lenght and widht of resulting image
     * and set the parameters dim_x and dim_y
     *
     * @access  private
     * @return  bool
    */
    function _image_dimension()
    {
        $this->fontWidth = imagefontwidth($this->font);
        $font_height = imagefontheight($this->font);
        $tot_char_width = 0; //total width of array in character
        if (($this->cols == 0) || ($this->rows == 0)) {
             $this->_max_cells_width();
        }
        reset($this->arr);
        while (list($i,$num_char) = each($this->arr['width'])) {
            $tot_char_width += $num_char;
        }
        $this->row_height = $font_height + 2 * $this->cellspacing ;
        //resulting image's dimension in pixel
        $this->dim_x = $tot_char_width * $this->fontWidth + $this->cols * 2 * $this->cellspacing + 1;
        $this->dim_y = ($this->rows-1) * ($this->row_height) + 1;
        return($this->flag);
    }

    /**
     * Calculate the maximun width as number of character
     * for each column of the original bidimensional array
     * It adds a row to the array :
     * $this->array[width] = array(); 
     * and then sets the parameters $rows, $cols
     *
     * @access  private
     * @returns void
    */
    function _max_cells_width()
    {
        $this->arr['width'] = array();
        $this->rows = 0;
        $this->cols = 0;
        reset($this->arr);
        while (list($row_key,$row) = each($this->arr)) {
            while (list($col_key,$elem) = each($row)) {
                $width = strlen($elem);
                if (($this->arr['width'][$col_key] < $width) and ($row_key != 'width')) {
                    $this->arr['width'][$col_key] = $width;
                }
            }
            $this->rows++;
        }
        $this->cols = count($this->arr['width']);
    }//end func _max_cells_width

} //end of class array_to_image

?>
Return current item: array_to_image