画像に影付きの日本語文字を施すのは前回と同じですが、一文字ずつ色を変えるようにしてみます。



■ソースコード
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);


// 400x90キャンバスを作成して内部イメージ取得
$img= imagecreatetruecolor(400, 90);



// 色を作成
$black= imagecolorallocate($img, 0, 0, 0); // 影、枠
$white= imagecolorallocate($img, 255, 255, 255); // 背景
// 文字用のランダムな色を50種類生成
foreach (range(1, 50) as $i){
    $color[]= imagecolorallocate($img,
    rand(0, 255), rand(0, 255), rand(0, 255));
}



// 背景色を白に
imagefill($img, 0, 0, $white);



// 文字入れ準備(文字コードUTF-8)
$text= <<<EOT
PHPで画像処理
GDライブラリ!
EOT;
$text= mb_convert_encoding($text, "UTF-8", "SJIS-win");



// 先に影になる文字入れ
colortext($img, 28, 0, 40+4, 36+4, array($black), 'C:\mo.ttf', $text);


// ぼかす
imagefilter($img, IMG_FILTER_GAUSSIAN_BLUR);
imagefilter($img, IMG_FILTER_GAUSSIAN_BLUR);


// 文字入れ
colortext($img, 28, 0, 40, 36, $color, 'C:\mo.ttf', $text);



// 黒枠で囲む
imagerectangle($img, 0, 0, 399, 89, $black);



// 画像をブラウザに出力
header("Content-type: image/png");
imagepng($img);



// メモリを解放
imagedestroy($img);



function colortext($img, $size, $angle, $x, $y, $color, $ttf, $text)
{
    mb_internal_encoding("UTF-8");
    $text= mb_convert_encoding($text, "UTF-8", "UTF-8,SJIS-win,CP51932,JIS");


    $w= '';
    for ($xx=$x,$yy=$y,$i=$j=0,$c=$color[0];
    ($t=mb_substr($text, $i++, 1)) != "";
    $c=(isset($color[++$j]) ? $color[$j] : $color[$j=0])){


        if (preg_match('/^[\x0d\x0a]+$/', $t)){


            // 改行補正
            if ($t === "\x0d" && mb_substr($text, $i, 1) === "\x0a"){
                $i++; $t= "\x0d\x0a";
            }


            $q= imagettfbbox($size, $angle, $ttf, $t . "A");
            $yy+= $q[1]+1; $xx= $x;
            $w= '';
            continue;
        } else {


            $w.= $t;
            if ($w !== $t){
                $q= imagettfbbox($size, $angle, $ttf, $w);
                $xx= $q[2]+$x- intval($size/2);
            }
        }


        imagettftext($img, $size, $angle, $xx, $yy, $c, $ttf, $t);
    }
}


?>



[表示結果]
そろそろホンキ出す-PHP GD



imagettftext()関数やimagettfbbox()関数の戻り値では正確な次の文字の印字位置が判らなかった(マニュアルにも載ってないしググってもどこにもな~い!)ので独自に決め打ちするしかありませんでした。


用途はあまりなさそうですが、練習がてら作ってみました。


なんか腑に落ちないですが、これで完成ということにしておきます。