Tag: multicolor image

  • How to create multicolor text image on the fly

    This tutorial explains how we can create dynamic images with multicolor text in PHP.

    We will need GD library and FreeType library to be enabled for this functionality to work.

    I have assumed that you already know PHP, and understand how to use it.

    Check the example below to see what we want to create.

    Amit Singh

    Before we start the tutorial, let’s check if GD library support is available on your system or not.

    Type phpinfo(); in a php file, and check the output.

    phpinfo_gd

    You should see something like that you can move forward, else goto php.ini and remove the comment from extension=php_gd2.dll. Now check phpinfo() again to verify that every thing is ok.

    Now, let see how we can create dynamic images using PHP.

    CODE

    Header ("Content-type: image/png");
    
    putenv('GDFONTPATH=' . realpath('.'));
    $font = 'nevis.ttf';
    $fontSize=20;//in point;
    
    $title1= 'Amit';
    
    $title2= 'Singh';
    
    $str=$title1.'   '.$title2;
    
    $onecharwidth  = imagefontwidth($font)*($fontSize/8);
    
    $totalwidth  = $onecharwidth * strlen($str);
    
    $height = (imagefontheight($font)*($fontSize/8))*2;
    
    $img_handle = imagecreatetruecolor($totalwidth, $height);
    
    $white = imagecolorallocate($img_handle, 255, 255, 255);
    
    imagefill($img_handle, 0, 0, $white);
    
    $black = imagecolorallocate ($img_handle, 0, 0, 0);
    
    $gray = imagecolorallocate ($img_handle, 100, 100, 100);
    
    imagettftext($img_handle, 20, 0, 10, 20, $black, $font, $title1);
    
    $posarr=imagettfbbox(20, 0,$font, $title1);
    
    imagettftext($img_handle, 20, 0, $posarr[2]+$onecharwidth, 20, $gray, $font, $title2);
    
    imagepng ($img_handle);
    
    imagedestroy ($img_handle);

    (more…)