how to create an outline on text or digits with gd and php

Like this simple example : gd outline

Sample code :




<?php
$string = "10€";
$font = "./arial.ttf";

// Adapted from http://www.phpbuilder.com/columns/cash20030526.php3?print_mode=1
// &
// http://www.php.net/manual/fr/function.imagettftext.php

header('Content-type: image/png');

// Image building
$im = imagecreatetruecolor(70, 70);

// Colors definitions
$white = imagecolorallocate($im, 255, 255, 255);
$yellow = imagecolorallocate($im, 255, 255, 0);
$purple =  imagecolorallocate($im, 89, 3, 255);
//$grey = imagecolorallocate($im, 128, 128, 128);
//$black = imagecolorallocate($im, 0, 0, 0);
//$red = imagecolorallocate($im, 255, 22, 5);

imagefilledrectangle($im, 0, 0, 70, 70, $white);

function imagettftextoutline(&$im,$size,$angle,$x,$y,&$col,
            &$outlinecol,$fontfile,$text,$width) {
    // For every X pixel to the left and the right
    for ($xc=$x-abs($width);$xc<=$x+abs($width);$xc++) {
        // For every Y pixel to the top and the bottom
        for ($yc=$y-abs($width);$yc<=$y+abs($width);$yc++) {
            // Draw the text in the outline color
            $text1 = imagettftext($im,$size,$angle,$xc,$yc,$outlinecol,$fontfile,$text);
        }
    }
    // Draw the main text
    $text2 = imagettftext($im,$size,$angle,$x,$y,$col,$fontfile,$text);
}

imagettftextoutline(
        $im,           // image location ( you should use a variable )
        20,            // font size
        0,             // angle in °
        0,             // x
        25,            // y
        $yellow,
        $purple,
        $font,
        $string,       // pattern
        2              // outline width
);

imagepng($im);
imagedestroy($im);
?>


Une réponse à “how to create an outline on text or digits with gd and php”

  1. Kevin dit :

    I modified the original function to provide rounded edges. Basically it’s just an if statement that checks to see if the x squared and y squared sum is less than the outline width squared.

    http://pastebin.com/MaM2xxVj

    Thanks for this code, you really helped me out.

Laisser un commentaire