+ Reply to Thread
Page 1 of 6
1 2 3 ... LastLast
Results 1 to 10 of 51

Thread: PHP:Tutorial - Getting to know GD

  1. #1
    Co-Administrator John is a glorious beacon of light John is a glorious beacon of light John is a glorious beacon of light John is a glorious beacon of light John is a glorious beacon of light John's Avatar
    Join Date
    Jul 2006
    Age
    21
    Posts
    5,883
    Blog Entries
    25

    PHP:Tutorial - Getting to know GD

    Title: Create dynamic userbars with GD

    Introduction:
    Have you ever been on aim and received a message from one of your friends with a big long URL followed by something like "John%20Is%20Stupid." You know what ever it is, wont be worth your time, but you click on it anyway to find someone goofy looking holding a sign and on it printed in big bold letters “John Is Stupid.” Ever wonder how they work? Chances are the script takes advantage of the GD functions. In this tutorial you will learn many GD functions that you can use to generate images. The goal for this tutorial is for you to generate a dynamic user bar.

    Here is a list of the functions used in this tutorial:
    header()
    imagecolorallocate()
    imagettfbbox()
    imagesx()
    abs()
    imagettftext()
    imagepng()
    imagedestroy()

    Solution:
    The first thing you want to do is create the header type using the header function. Next you use the GD tools to create an image from a png file. In my case, I have userbar.png in the same directory as this script is in. The function imagecolorallocate creates a color using RGB (red-green-blue) format. The next three lines just set some basic information which isn’t that hard to understand. The last three lines to must of the work creating the image. The most important function here to pay attention to is imagettftext. The imagettftext requires 8 arguments which are the resource image, font size, the angle, x location, y location, font color, the actual font, and the string to be printed.

    Code:
    <?php
    header
    ('Content-type: image/png');
    $im imagecreatefrompng ("userbar.png");
    $color imagecolorallocate($im000);
    $text "test";
    $font 'font.ttf';
    $size 8;
    imagettftext($im$size01512$color$font$text);
    imagepng($im);
    imagedestroy($im);
    ?>
    Now that we have GD generating an image, lets make it a little more complex. We’ve added the
    Code:
    $text $_GET['text']; 
    line to allow the user to enter a random string, and we have also added the
    Code:
     $size imagettfbbox($fontsize0$font$text);
    $dx = (imagesx($im)) - (abs($size[2]-$size[0])) - 20
    Which calculate where to start printing the string on the image. The function imagettfbbox generates the length of the font string in pixels. If you were to use something like strlen($text) that would just return the number of characters in the string, which isn’t very usefull in this case. Next, we use the imagesx() function to determine the width of the image, we take that value and subtract the string length in pixels and subtract an extra 20 pixels to leave some room toward the end of the image.
    Code:
    <?php
    header
    ('Content-type: image/png');
    $text $_GET['text'];
    $im imagecreatefrompng ("userbar.png");
    $color imagecolorallocate($im000);
    $font 'font.ttf';
    $fontsize 6;
    $size imagettfbbox($fontsize0$font$text); //calculate the pixel of the string
    $dx = (imagesx($im)) - (abs($size[2]-$size[0])) - 20//calculate the location to start the text
    imagettftext($im$fontsize0$dx13$color$font$text);
    imagepng($im);
    imagedestroy($im);
    ?>
    At this point you could call yourself done. However you could add some extra features such as make the font color vary with the user input. Adding a simple if statement will accomplish this.

    Code:
    <?php
    header
    ('Content-type: image/png');
    $text $_GET['text'];

    $im imagecreatefrompng ("userbar.png");

    if(
    $text == "ADMINISTRATOR"){ //if administrator
        
    $color imagecolorallocate($im25500); //red
        

    elseif(
    $text == "MODERATOR"){ //if moderator
        
    $color imagecolorallocate($im00255); //blue
        

    elseif(
    $text == "JUNKIE"){ //if junkie
        
    $color imagecolorallocate($im000); //black
        

    else { 
    //something else...
        
    $color imagecolorallocate($im01280); //green
        
    }
        
    $font 'font.ttf'//font file
    $fontsize 6//font size
    $stringsize imagettfbbox($fontsize0$font$text); //calculate the pixel of the string
    $dx = (imagesx($im)) - (abs($stringsize[2]-$stringsize[0])) - 20//calculate the location to start the text
    imagettftext($im$fontsize0$dx13$color$font$text);
    imagepng($im);
    imagedestroy($im);
    ?>
    Finally you can save this script as generator.php and display it in forums by using the html tags.

    Code:
    <img src="http://www.yourdomain.com/generator.php?text=JUNKIE" />
    This post was originally written for johnciacia.com and may not be reused or reposted without consent from the author.
    Attached Files
    Last edited by John; 01-04-2010 at 04:56 PM.

  2. #2
    Co-Administrator John is a glorious beacon of light John is a glorious beacon of light John is a glorious beacon of light John is a glorious beacon of light John is a glorious beacon of light John's Avatar
    Join Date
    Jul 2006
    Age
    21
    Posts
    5,883
    Blog Entries
    25
    Here are two more scripts that take advantage of GD, I've posted these before but I figured i'll post them here to keep track of them.

    Captcha Generator
    Code:
    <?php
    function RandomStringGenerator($length){
    global 
    $string;
        
    $pattern "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
    if(empty(
    $length)){
        
    $length "10";
        }
    for(
    $i=0$i<$length$i++){
        
    $string .= $pattern{rand(0,61)};
        }

    return 
    $string;
    }

    function 
    CaptchaGenerator(){
    global 
    $string;
    RandomStringGenerator();
    header("Content-type: image/png");
    $im = @imagecreate(10050)
       or die(
    "Cannot Initialize new GD image stream");
    $background_color imagecolorallocate($im000);
    $text_color imagecolorallocate($im25500);
    imagestring($im1055,  $string$text_color);
    imagepng($im);
    imagedestroy($im);
    }

    CaptchaGenerator(); 
    ?>
    Signature Rotator/Banner Rotator:

    Code:
    <?php

    $folder 
    './';

    $extList = array();
    $extList['gif'] = 'image/gif';
    $extList['jpg'] = 'image/jpeg';
    $extList['jpeg'] = 'image/jpeg';
    $extList['png'] = 'image/png';

    $img null;

    if (
    substr($folder,-1) != '/') {
       
    $folder $folder.'/';
    }

    if (isset(
    $_GET['img'])) {
       
    $imageInfo pathinfo($_GET['img']);
       if (
           isset( 
    $extListstrtolower$imageInfo['extension'] ) ] ) &&
           
    file_exists$folder.$imageInfo['basename'] )
       ) {
           
    $img $folder.$imageInfo['basename'];
       }
    } else {
       
    $fileList = array();
       
    $handle opendir($folder);
       while ( 
    false !== ( $file readdir($handle) ) ) {
           
    $file_info pathinfo($file);
           if (
               isset( 
    $extListstrtolower$file_info['extension'] ) ] )
           ) {
               
    $fileList[] = $file;
           }
       }
       
    closedir($handle);

       if (
    count($fileList) > 0) {
           
    $imageNumber time() % count($fileList);
           
    $img $folder.$fileList[$imageNumber];
       }
    }

    if (
    $img!=null) {
       
    $imageInfo pathinfo($img);
       
    $contentType 'Content-type: '.$extList$imageInfo['extension'] ];
       
    header ($contentType);
       
    readfile($img);
    } else {
       if ( 
    function_exists('imagecreate') ) {
           
    header ("Content-type: image/png");
           
    $im = @imagecreate (100100)
               or die (
    "Cannot initialize new GD image stream");
           
    $background_color imagecolorallocate ($im255255255);
           
    $text_color imagecolorallocate ($im0,0,0);
           
    imagestring ($im255,  "IMAGE ERROR"$text_color);
           
    imagepng ($im);
           
    imagedestroy($im);
       }
    }

    ?>
    To add a border to text:
    Code:
    /**
     * Writes the given text with a border into the image using TrueType fonts.
     * @author John Ciacia < John@extreme-hq.com >
     * @param image An image resource.
     * @param size The font size.
     * @param angle The angle in degrees to rotate the text.
     * @param x Upper left corner of the text.
     * @param y Lower left corner of the text.
     * @param textcolor This is the color of the main text.
     * @param strokecolor This is the color of the text border.
     * @param fontfile The path to the TrueType font you wish to use.
     * @param text The text string in UTF-8 encoding.
     * @param px Number of pixels the text border will be.
     * @return Returns an array with 8 elements representing four points making the bounding 
     *         box of the text. The order of the points is lower left, lower right, upper right, 
     *         upper left. The points are relative to the text regardless of the angle, so 
     *         "upper left" means in the top left-hand corner when you see the text horizontally.
     * @see http://us.php.net/manual/en/function.imagettftext.php
     * @see http://forum.codecall.net
     * @see http://www.extreme-hq.com
     */
    function imagettfstroketext(&$image$size$angle$x$y, &$textcolor, &$strokecolor$fontfile$text$px) {

        for(
    $c1 = ($x-abs($px)); $c1 <= ($x+abs($px)); $c1++)
            for(
    $c2 = ($y-abs($px)); $c2 <= ($y+abs($px)); $c2++)
                
    $bg imagettftext($image$size$angle$c1$c2$strokecolor$fontfile$text);

       return 
    imagettftext($image$size$angle$x$y$textcolor$fontfile$text);

    Usage:
    Code:
    $img imagecreatefrompng("/home/john/Desktop/test.png");
    $font_color imagecolorallocate($img000);
    $stroke_color imagecolorallocate($img25500);
    $font "/home/john/Desktop/ABSTRACT.TTF";
    $txt "This is a test..";
    $px 2;
    imagettfstroketext($img1001050$font_color$stroke_color$font$txt$px); 
    Enjoy!
    Last edited by John; 05-04-2008 at 01:37 PM.

  3. #3
    Administrator Jordan is a name known to all Jordan is a name known to all Jordan is a name known to all Jordan is a name known to all Jordan is a name known to all Jordan is a name known to all Jordan's Avatar
    Join Date
    Nov 2005
    Location
    Hendersonville, NC
    Posts
    24,556
    Blog Entries
    97
    Nice Tutorial, very well done.

  4. #4
    TcM
    TcM is offline
    Code Warrior TcM is a name known to all TcM is a name known to all TcM is a name known to all TcM is a name known to all TcM is a name known to all TcM is a name known to all TcM's Avatar
    Join Date
    Aug 2006
    Posts
    11,461
    Blog Entries
    6
    :0 Im impressed I wish I knew PHP

  5. #5
    Co-Administrator John is a glorious beacon of light John is a glorious beacon of light John is a glorious beacon of light John is a glorious beacon of light John is a glorious beacon of light John's Avatar
    Join Date
    Jul 2006
    Age
    21
    Posts
    5,883
    Blog Entries
    25
    Thanks for the comments, ive added 2 more scripts to this section that you've already seen but also take advantage of GD so i figured they were worth showing

  6. #6
    TcM
    TcM is offline
    Code Warrior TcM is a name known to all TcM is a name known to all TcM is a name known to all TcM is a name known to all TcM is a name known to all TcM is a name known to all TcM's Avatar
    Join Date
    Aug 2006
    Posts
    11,461
    Blog Entries
    6
    I have a problem with the 1st tutorial.. I made this:-
    Code:
    <html>
    <img src="http://localhost/generator.php?text=ADMINISTRATOR" />
    </html>
    Right? its localhost because I ran a Server on my PC to try this.. and it supports PHP but the image link is showing as broken.. any idea why?
    I even tried to upload it to a hosting site that supports php.. still broken link...
    Last edited by TcM; 12-04-2006 at 11:54 PM.

  7. #7
    Administrator Jordan is a name known to all Jordan is a name known to all Jordan is a name known to all Jordan is a name known to all Jordan is a name known to all Jordan is a name known to all Jordan's Avatar
    Join Date
    Nov 2005
    Location
    Hendersonville, NC
    Posts
    24,556
    Blog Entries
    97
    I'm betting you do not have GD working or compiled into your system. Is it a Windows System?

    Create a PHP file named phpinfo.php and put this in it:

    Code:
    <?php
    phpinfo
    ();
    ?>
    Then goto http://localhost/phpinfo.php - this lists everything that your PHP can do. Search for GD.

  8. #8
    TcM
    TcM is offline
    Code Warrior TcM is a name known to all TcM is a name known to all TcM is a name known to all TcM is a name known to all TcM is a name known to all TcM is a name known to all TcM's Avatar
    Join Date
    Aug 2006
    Posts
    11,461
    Blog Entries
    6
    Well when I tried localhost/phpinfo.php nothing cameup.. perhaps its not configured correctly but then I tried it on a hosting site yes it is Enabled!!:-
    gd
    GD Support enabled
    GD Version bundled (2.0.28 compatible)
    FreeType Support enabled
    FreeType Linkage with freetype
    GIF Read Support enabled
    GIF Create Support enabled
    JPG Support enabled
    PNG Support enabled
    WBMP Support enabled
    XBM Support enabled
    I opened the PHP file generator.php ( on the hosting site )and it said:-
    The image “http://tcm9669.9999mb.com/generator.php” cannot be displayed, because it contains errors.
    huh??
    Last edited by TcM; 12-04-2006 at 02:04 PM.

  9. #9
    Co-Administrator John is a glorious beacon of light John is a glorious beacon of light John is a glorious beacon of light John is a glorious beacon of light John is a glorious beacon of light John's Avatar
    Join Date
    Jul 2006
    Age
    21
    Posts
    5,883
    Blog Entries
    25
    If your running this script on a linux server, i believe the font i included is called font.TTF not font.ttf
    Last edited by John; 12-05-2006 at 12:23 AM.

  10. #10
    TcM
    TcM is offline
    Code Warrior TcM is a name known to all TcM is a name known to all TcM is a name known to all TcM is a name known to all TcM is a name known to all TcM is a name known to all TcM's Avatar
    Join Date
    Aug 2006
    Posts
    11,461
    Blog Entries
    6
    Well the hosting site would not let me upload .tff just .TFF .. Dam them! Well never mind I just wanted to try it!! but still nice tut...

+ Reply to Thread
Page 1 of 6
1 2 3 ... LastLast

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

     

Similar Threads

  1. PHP:Tutorial - Email Verification
    By John in forum PHP Tutorials
    Replies: 3
    Last Post: 09-19-2007, 12:19 PM
  2. PHP:Tutorial The Date
    By John in forum PHP Tutorials
    Replies: 0
    Last Post: 01-10-2007, 06:10 PM

Bookmarks

Bookmarks

     
        Algorithms and Data Structures

        Java tutorials

        Algorithms Forum

Posting Permissions

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