現在の位置: ホーム> 最新記事一覧> php imagestring()関数使用チュートリアル:画像に水平テキストを描く

php imagestring()関数使用チュートリアル:画像に水平テキストを描く

gitbox 2025-07-18

Imagestring()関数の紹介

PHPでは、 Imagestring()は、画像に水平テキストを描画するための組み込み関数です。検証コードの生成や画像テキストへの注釈などのシナリオで広く使用されており、特に簡単なテキストコンテンツの出力に迅速に出力するのに適しています。

関数の基本的な構文は次のとおりです。

 bool imagestring ( resource $image , int $font , int $x , int $y , string $string , int $color )

各パラメーターの意味は次のとおりです。

  • $画像:通常、 ImageCreatetrueColor()またはImageCreate()によって作成された画像リソース。
  • $ font :システムには、1〜5の範囲の値が組み込まれています。
  • $ x :テキスト描画の開始x座標。
  • $ y :テキスト図面の開始y座標。
  • $文字列:描画するテキスト文字列。
  • $ COLOR :Text Color、 ImageColorAllocate()によって設定されています。

画像リソースを作成します

Imagestring()を使用する前に、画像リソースを作成する必要があります。次のコードは、500×500ピクセルの空白の画像を作成します。

 $im = imagecreatetruecolor(500, 500);

色とフォントを設定します

次に、使用されるテキストの色、背景色、フォントを定義します。

 $font = 4; // 内蔵フォントサイズ
$color = imagecolorallocate($im, 0, 0, 0); // 黒いテキスト
$background = imagecolorallocate($im, 255, 255, 255); // 白い背景

画像にテキストを描きます

画像と色の設定を完了したら、テキストを画像に描画できます。次の例には、「Hello World!」という例が描かれています。調整する(50、50):

 imagestring($im, $font, 50, 50,  "Hello world!", $color);

完全な例:画像の中心にテキストを描く

「Hello World!」というテキストを使用する完全な例を次に示します。画像の中央に描画され、PNG形式に出力が描画されます。

 $im = imagecreatetruecolor(500, 500);
$white = imagecolorallocate($im, 255, 255, 255);
$red = imagecolorallocate($im, 255, 0, 0);
imagefill($im, 0, 0, $white);

$font = 1;
$x = imagesx($im) / 2 - imagefontwidth($font) * strlen("Hello World!") / 2;
$y = imagesy($im) / 2 - imagefontheight($font) / 2;

imagestring($im, $font, $x, $y, "Hello World!", $red);

header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);

要約します

Imagestring()は、PHPの非常に実用的な画像処理機能であり、画像にテキストをすばやくレンダリングするのに適しています。カラー設定と調整位置付けにより、特に検証コードや動的画像テキストの透かしなどのアプリケーションに適したさまざまなテキスト画像出力を柔軟に生成できます。