PHP和GD库为文本添加1px实线边框?我得到了像点一样的边框

时间:2015-07-16 11:35:06

标签: php border gd

以下是我收到的文字:

test

我想为文字添加一个实线边框,即使边框是纯黑色......

这是我的代码:

<?php
    $text = ($_GET['txt'] ? $_GET['txt'] : '?');
    $text = strtoupper($text[0]).substr($text,1,strlen($text));
    $size = ($_GET['size'] ? $_GET['size'] : 15);
    $sizex = 120;
    $sizey = 28;
    $x = 4;
    $y = 20;
    $color = ($_GET['color'] ? $_GET['color'] : 'efcfa4');
        $red = (int)hexdec(substr($color,0,2));
        $green = (int)hexdec(substr($color,2,2));
        $blue = (int)hexdec(substr($color,4,2));
    $img = imagecreatetruecolor($sizex,$sizey);
    ImageColorTransparent($img, ImageColorAllocate($img,0,0,0));

    imagettftext($img, $size, 0, $x, $y, ImageColorAllocate($img,$red,$green,$blue), 'martel.ttf', $text);

    header('Content-type: image/png');
    imagepng($img);
    imagedestroy($img);
?>

使用文本数据生成的图片是从另一页的此行中获取的:

<img src="pages/scripts/font1.php?txt=test&color=cccccc&size=15">

1 个答案:

答案 0 :(得分:1)

你可以这样做。

<?php

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);
}

// Create new canvas
$im = imagecreatetruecolor(170,  60);

// Set background to white
$gray = imagecolorallocate($im, 100, 100, 100);
imagefill($im, 0, 0, $gray);

// Set fron color and border color
$font_color = imagecolorallocate($im, 255, 255, 255);
$stroke_color = imagecolorallocate($im, 0, 0, 0);

//image, fontsize, angle, x, y, textcolor, bordercolor, font file, text, borderwidth
imagettfstroketext($im, 60, 0, 10, 50, $font_color, $stroke_color, "martel.ttf", "test", 2);

// Output
header('Content-type: image/jpg');
imagejpeg($im);
imagedestroy($im);
?>