Results 1 to 1 of 1
  1. #1

    Lightbulb Replace HTML Spacing for Poll Result Bar with PHP GD Image Generation (Intermediate)

    Creating Automatic Poll Bar Generator
    In this article we will learn how to create Poll Bar Image through PHP GD Functions.I tried to replace the conventional poll result bar with PHP GD
    In which I use Gradient Spacers and Image Icon, and Combine into One Image.
    Example
    http://www.zaheema.com/votebar/images/7.gif
    Usage:
    I have created this Poll Bar Generator Class, to show rating for My Client Testimonial page. You can achieve this by HTML Spacing as well, but I think single GIF file is more efficient solution for it.

    DEMO:
    http://www.zaheema.com/votebar/images/5.gif
    http://www.zaheema.com/votebar/images/1.gif
    DOWNLOAD Source + DOCX Format Tutorial
    (Not Sure to put Clickable Link thats why hiding it in CODE)


    IDEA:
    The Process of Creating the bar is exactly, same like HTML Display Poll bar; first we will spread the main spacer, and then calculate the Voting Result, and spread the Vote Bar spacer accordingly. And at the end we will add User Icon at the End of Bar (Client Testimonial Icon)
    What We Will Achieve
    In this article, we will learn how to use GD Function to
    • create Image Platte
    • How to Resize the Image
    • How to copy Image on the Platte
    • Apache Mod_Rewrite and SEO, Short URL
    Requirements
    • PHP 4.1.x (TESTED WITH PHP 5)
    • GD 2.0
    Optional
    Apache with Mod_Rewrite Engine (If you use Apache Part as well)

    PHP Functions used in this Article, Their Usage and Explanation

    array getimagesize ( string $filename [, array &$imageinfo] )
    It is GD Function, which return the array, filled with Image Information like Dimension, Mime
    etc
    Example
    PHP Code:
    $array =getimagesize(“polls/icon1.gif”); 
    Output (Format)
    Array[0] = Width
    Array[1] = Height
    Array[2] = Image Type Flag
    Array[3] = width="xxx" height="xxx"
    Array[bits] = bits
    Array[channels] = channels
    Array[mime] = mime-type

    We will use this function to get the Height the our Main Canvas, and Mime Type (gif/jpeg) for Our Output to browser

    resource imagecreatefromgif ( string $filename )
    Another Useful GD function, You can create Image from Path or URL by this function and load image into memory (resource), We need to load our image into resource before applying any function like resizing or overlaying. So we load all our Images to create Bar, into Resource First through This Function.
    If Our Mime Type of Image is JPEG then we use imagecreatefromjpeg

    resource imagecreatetruecolor ( int $width, int $height )
    Use this function to create Image (For Ouput), Do not get confuse, by imagecreatefromgif we will load our images and paste into Canvas draw by this function

    bool imagecopyresized ( resource $dst_image, resource $src_image, int $dst_x, int $dst_y, int $src_x, int $src_y, int $dst_w, int $dst_h, int $src_w, int $src_h )
    It is the Key PHP Function, to implement our Idea, as the name reveal that it is use for resizing image.
    You will see later it in action, then you will understand how it works.

    bool imagecopy ( resource $dst_im, resource $src_im, int $dst_x, int $dst_y, int $src_x, int $src_y, int $src_w, int $src_h
    The Last PHP Builtin Function Used in this Class to achieve our IDEA, is use to copy the Image into another Image, like when we resize the image and then place it into main Stage. We will use this function then.

    int Imagesx(resource $img)
    Calculate the Width of Image loaded into resource

    Integer Imagesy(resource $img)
    Calculate the Height of Image loaded into resource

    Thinking Programmatically
    As I have told you earlier in IDEA Section, that we actually resize and overlay image, so obviously we need either three variables or arrays to hold the location of our images plus we need two more to control output, one will decide the overall size of Poll Bar, and other will decide the Fill Bar for Vote, like above Green in Image. So, our Class has following Main
    Variables.
    PHP Code:
    Class barGenerator
        
    {
        var 
    $image_location;    //Array, Images Location
        
    var $height;        //Integer, Height of Bar
        
    var $width;         //Integer, Total Width of Bar
        
    var $x_icon;        //Distance of X Coordinate of Icon Image in Main Canvas
        
    var $ratio;        //Ratio to Multiply the Given Width, (Will be Clear in Context)    var $vote;        //Number of Votes
     
    // Now Creating the Main Constructor Function for our Class, and fill the above Variables with  // values, The Main Function will accept, two variables, Bar Size, and Vote/Rating (1 to 10) 
    function barGenerator($size,$vote)
    {
    $this->width=$size;
    $this->vote=$vote;
    // As you can see the Vote is in between 1 to 10, so we will multiply the ratio with vote value to 
    // get the exact size for Vote Green Bar
    $this->ratio=$this->width/10;
    $this->image_location=array();
    $this->image_location[‘spacer_background’]=$this->getCurrentDir().”/polls/fill_spacer.gif”;
    $this->image_location[‘spacer_vote’]=$this->getCurrentDir().”/polls/fill_fill.gif”;
    $this->image_location[‘icon’]=$this->getCurrentDir().”/polls/fill_icon.gif”;
    }
     
    // Child Function of Class to Draw and Output The Bar
    Function drawbar()
    {
    // First we load the Image Locations into Resource so we can Resize them
    /*
    You can see that first I get the information of image through getimagesize function
    then apply the condition and run GD Function accordingly to create image (Resource)
    */
    $info_spacer getimagesize($this->image_location[‘spacer_background’]);
    if ($info_spacer['mime']=="image/gif")
                 
    $convas_spacer=imagecreatefromgif($this->image_location['spacer_background']);
                    else if (
    $info['mime']=="image/pjpeg" || $info['mime']=="image/jpeg")                               $convas_spacer=imagecreatefromjpeg($this->image_location['spacer_background']);
     
    $info_image getimagesize($this->image_location[‘spacer_vote’]);
    if ($info_image['mime']=="image/gif")
         
    $vote_spacer=imagecreatefromgif($this->image_location[‘spacer_vote’]);
    else if ($info_image['mime']=="image/pjpeg" || $info['mime']=="image/jpeg")
         
    $vote_spacer=imagecreatefromjpeg($this->image_location[‘spacer_vote’]);
     
    $info_icon getimagesize($this->image_location['icon']);
    if (
    $info_icon['mime']=="image/gif")
         
    $iconimg=imagecreatefromgif($this->image_location['icon']); 
    else if (
    $info_icon['mime']=="image/pjpeg" || $info['mime']=="image/jpeg")
         
    $iconimg=imagecreatefromjpeg($this->image_location['icon']);
     
    // Storing the Dimension of Image into Variables
    $this->x_icon=$this->width;
    $this->width=$this->width+$info_icon[0];
    $this->height=$info_icon[1];
    //    verify that we have successfully loaded the image into memory
    if(!is_resource($convas_spacer) || !is_resource($vote_spacer) || !is_resource($iconimg))
    {
    echo 
    "Cannot Load Image Files, Script Halt";
    exit;
        }
        
    // creating a Full Background Spacer, according to Size Specified
    // Height is automatically Calculated from Spacer Image
        
    $background=imagecreatetruecolor($this->width,$info_spacer[1]);
        
    // imagesy function used to calculate the Height of Image in Memory, and imagex for Width
        
    $height=imagesy($convas_spacer);
        
    // Fill it with Spacer 
        /*
        Usuage: imagecopyresized
        $background is destination Image
        $convas_spacer is Spacer for Background (First Image)
        0,0 are the Destination X and Y Cordinates (for to start from)
        0,0 are the Source X and Y Cordinates (for to start from)
        this->total_size*$this->total_size  is percent of width to spread, as it is main spacer so i spread  
         it all
        imagesy() function return the Height of the Loaded Resource Image as you can see we have
        loaded $convas_spacer in memory earlier
        $this->Width width of Resource Image
        $height Height of Resource Image
        Next Parameter is Resource Image Width, 
        and Height is calculated through imagesy() of loaded image, earlier
        */
    imagecopyresized($background,$convas_spacer,0,0,0,0,
    $this->width*$this->width,$height,$this->width,imagesy($convas_spacer)); 
        
    //Calculating the Width of Vote Background
        
    $vote_bg_length=$this->vote $this->ratio+10;
    //$vote_bg_length=$vote_bg_length-10;
        
    $vote_bg=imagecreatetruecolor($vote_bg_length,$height);
        
    imagecopyresized($vote_bg,$vote_spacer,0,0,0,0
    ,imagesx($vote_bg)*$this->ratio*100,imagesy($vote_bg),$this->width,$height); 
     
        
    //Copy the Vote_bg spacer (spread) and Icon Image into the Main $background 
        /*
        ImageCopy
        $background main Convas or Destinatino Image
        $vote_bg The Resource Image to be copy, ( as we have created above)
        0,0,0,0 Cordinates (No Explanation Needed)
        $vote_bg_length is length of Vote Convas (already Declared)
        $vote
        */
                
    imagecopy($background,$vote_bg,0,0,0,0,imagesx($vote_bg),imagesy($vote_bg));
    imagecopy($background,$iconimg,
    $this->x_icon,0,0,0,imagesx($iconimg),imagesy($iconimg));                
    //SENDING OUTPUT TO BROWSER    
                    
    if ($info_spacer['mime']=="image/gif"
        {
        
    header("Content-type: image/gif");
        
    imagegif($background);
                     }  
                       else if (
    $info_spacer['mime']=="image/pjpeg" || $info_spacer['mime']=="image/jpeg"
        {
        
    header("Content-type: image/jpeg");
        
    imagejpeg($background);
                     }    
        
    //Free the Memory (Resource)            
        
    imagedestroy($background);
                   
    imagedestroy($vote_bg);
                       
    imagedestroy($iconimg);
    }
     
    // Extra Functions
        // Return The Current Directory
        
    function getCurrentDir()
        {
        return 
    getcwd();
        }

    Usage of Class
    You can execute the Class by Including and Executing the Class file Like Below
    PHP Code:
    <?php
    include_once "bargenerate.php";
    $image=new barGenerator(200,$_GET['width']);
    $image->drawbar();
    ?>
    Now you can see the Bar Code by
    http://yourdomain.com/classpath/index.php?width=7

    USER AND SEO FRIENDLY URL
    Though you can insert and show image by above URL but it is not User and Seo Friendly, if you want to create seo friendly urls, you just need to add .htaccess in class path directory, and you must sure that your Server Supports Mod_Rewrite Module.
    .htaccess
    Code:
    <IfModule mod_rewrite.c> 
         RewriteEngine on 
         RewriteRule images/(.*).gif index.php?width=$1
    </IfModule>
    The Third Line actually define the rule, to redirect classpath/images/ requests to index.php.
    Now you can access
    http://yourdomain.com/classpath/images/7.gif
    Last edited by mxdn; 05-30-2007 at 01:34 PM. Reason: Change The Clickable Url

  2. Newsletters

    Subscribe Now & Get The WHT Quick Start Guide!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •