PHPでは、 Imagestring()は、画像に水平テキストを描画するための組み込み関数です。検証コードの生成や画像テキストへの注釈などのシナリオで広く使用されており、特に簡単なテキストコンテンツの出力に迅速に出力するのに適しています。
関数の基本的な構文は次のとおりです。
bool imagestring ( resource $image , int $font , int $x , int $y , string $string , int $color )
各パラメーターの意味は次のとおりです。
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の非常に実用的な画像処理機能であり、画像にテキストをすばやくレンダリングするのに適しています。カラー設定と調整位置付けにより、特に検証コードや動的画像テキストの透かしなどのアプリケーションに適したさまざまなテキスト画像出力を柔軟に生成できます。