画像に日本語を表示してみる。
もともとある画像に文字列を挿入するプログラムを作ってみようと思う。
参考にしたサイト
環境の確認
参考サイト2から確認用スクリプトをコピペして環境が大丈夫なことを確認
<html> <body> <?php $buf_info = ""; $arrInfo = gd_info(); foreach ($arrInfo as $idx => $buf) { if (is_bool($buf)) { $buf_info .= "<p>" .htmlspecialchars("[$idx] ==>> " .($buf ? "OK" : "No Support")) ."</p>"; } else { $buf_info .= "<p>" .htmlspecialchars("[$idx] ==>> $buf") ."</p>"; } } echo $buf_info; ?> </body> </html>
字の描画
まず、字だけを描画してみる。imagecreate関数はではなく、imagecreatetruecolor関数を使用したほうがいいようなので、こちらを使用することにする。
<?php // コンテントタイプを設定する header("Content-type: image/png"); // 画像を生成する $im = imagecreatetruecolor(400, 30); // いくつかの色を生成する $white = imagecolorallocate($im, 255, 255, 255); $grey = imagecolorallocate($im, 128, 128, 128); $black = imagecolorallocate($im, 0, 0, 0); imagefilledrectangle($im, 0, 0, 399, 29, $white); // 描画する文字列 $text = 'Testing...'; // フォント自身のパスでパスを置き換える $font = 'dasaji_win.ttf'; // テキストに影を付ける imagettftext($im, 20, 0, 11, 21, $grey, $font, $text); // テキストを追加する imagettftext($im, 20, 0, 10, 20, $black, $font, $text); // imagepng() を使用して imagejpeg() よりもクリアなテキストにする imagepng($im); imagedestroy($im); ?>
画像に文字を入れる
もとのイメージソースに画像を持ってくればうまくいくんじゃないかと思い、ちょっくらためしてみる。
<?php // コンテントタイプを設定する header("Content-type: image/gif"); // 画像を生成する $im = imagecreatefromgif("salf.gif"); if($im) { // いくつかの色を生成する $white = imagecolorallocate($im, 255, 255, 255); $grey = imagecolorallocate($im, 128, 128, 128); $black = imagecolorallocate($im, 0, 0, 0); // 描画する文字列 $text = 'Testing...'; // フォント自身のパスでパスを置き換える $font = 'dasaji_win.ttf'; // テキストに影を付ける imagettftext($im, 20, 0, 11, 21, $grey, $font, $text); // テキストを追加する imagettftext($im, 20, 0, 10, 20, $black, $font, $text); // imagepng() を使用して imagejpeg() よりもクリアなテキストにする imagegif($im); imagedestroy($im); } ?>
左が文字無し、右が文字あり
感想
分かりやすい。これを利用して何か作ろう。