Draw text background colors in a PHP GD script

592 views Asked by At

I am trying to write text in a image with different colors, fonts and text background. For drawing text background, I am using 'imagefilledrectangle' function. At present, the script draws a background text color for each line of text in a foreach loop.

Now, I have two separate requirements.

(1) The script must draw background text color or rectangle in only first and last iteration of loop. In other words, I need background text color only against the first and last array of text, and not the middle ones.

(2) The script must produce text background color in each iteration of loop except the first and last. In other words, I do not need text background color just in first and last array text.

I need an idea how to do that.

Here is the complete script.

<?php

        $user = array(

        array(
            'name'=> 'Ashley Ford', 
            'font-size'=>'27',
            'color'=>'grey'),

        array(
            'name'=> 'Technical Director',
            'font-size'=>'16',
            'color'=>'grey'),

        array(
            'name'=> '[email protected]',
            'font-size'=>'13',
            'color'=>'green'
            )

    );

       function center_text($text, $size)
    {
        global $fontfile;
        global $image;
        // calculate position of text
        $tsize = imagettfbbox($size, 0, $fontfile, $text);
        $text_h = $tsize[7];
        $dx = abs($tsize[2] - $tsize[0]); // how wide is the text?
        $dy = abs($tsize[5] - $tsize[3]); // how tall is the text?
        $x = (imagesx($image) - $dx)/2;
        $y = (imagesy($image) - $dy)/2 + $dy;
        return array($dx, $text_h, $x, $y);
    }

    // link to the font file 
    $fontfile = 'XBall.ttf';

    // controls the spacing between text
    $i = 30;

    //JPG image quality 0-100
    $quality = 90;

    // Loan an existing image
    $image = imagecreatefromjpeg('weight-loss.jpg');

    // setup the text colors
    $color['grey'] = imagecolorallocate($image, 54, 56, 60);
    $color['green'] = imagecolorallocate($image, 55, 189, 102);

    $white = imagecolorallocate($image, 255, 255, 255);

    // this defines the starting height for the text block
    // $y = imagesy($image) - 365;

    // loop through the array and write the text
    foreach ($user as $value)
    {
        list($dx, $text_h, $x, $y) = center_text($value['name'], $value['font-size']);
        // Draw text background
        imagefilledrectangle($image, $x, $y + $text_h + $i, $x + $dx, $y + $i, $white);
        // Draw text
        imagettftext($image, $value['font-size'], 0, $x, $y + $i, $color[$value['color']], $fontfile, $value['name']);

        // add 32px to the line height for the next text block
        $i = $i+32;
    }

    header ('Content-Type: image/jpeg');
    imagejpeg($image);




?> 
0

There are 0 answers