imageloadfont()
ユーザー定義のビットマップをロードするために使用されます。Arial やその他の TrueType フォント (.ttf) または OpenType フォント (.otf) を使用したいだけの場合 (GD lib での後者のサポートにはバグがあります)、必要なのはimagettftext()
. ただし、テキストを使用して画像に書き込む前imagettftext()
に、まずそれが収まるかどうかを知る必要があります. これを知るには、電話するだけですimagettfbbox()
フォント サイズ、テキストの角度 (水平テキストの場合は 0)、.ttf または .otf フォント ファイルへのパス、およびテキスト自体の文字列を渡すと、4 つの点を表す 8 つの要素を含む配列が返されます。テキストの境界ボックス (詳細については、PHP のマニュアルを確認してください)。次に、これらの配列要素を参照して計算を実行し、特定のテキスト文字列が占める幅と高さを知ることができます。これらの値を使用して、テキスト全体を表示できる特定の幅と高さを持つ画像を作成できます。
以下は、開始するために実行しようとしていることを実行する簡単なスクリプトです。
<?php # Script 1
/*
* This page creates a simple image.
* The image makes use of a TrueType font.
*/
// Establish image factors:
$text = 'Sample text';
$font_size = 12; // Font size is in pixels.
$font_file = 'Arial.ttf'; // This is the path to your font file.
// Retrieve bounding box:
$type_space = imagettfbbox($font_size, 0, $font_file, $text);
// Determine image width and height, 10 pixels are added for 5 pixels padding:
$image_width = abs($type_space[4] - $type_space[0]) + 10;
$image_height = abs($type_space[5] - $type_space[1]) + 10;
// Create image:
$image = imagecreatetruecolor($image_width, $image_height);
// Allocate text and background colors (RGB format):
$text_color = imagecolorallocate($image, 255, 255, 255);
$bg_color = imagecolorallocate($image, 0, 0, 0);
// Fill image:
imagefill($image, 0, 0, $bg_color);
// Fix starting x and y coordinates for the text:
$x = 5; // Padding of 5 pixels.
$y = $image_height - 5; // So that the text is vertically centered.
// Add TrueType text to image:
imagettftext($image, $font_size, 0, $x, $y, $text_color, $font_file, $text);
// Generate and send image to browser:
header('Content-type: image/png');
imagepng($image);
// Destroy image in memory to free-up resources:
imagedestroy($image);
?>
必要に応じて値を変更してください。PHPのマニュアルを読むことを忘れないでください。