PHP Conference Japan 2024

imagefontheight

(PHP 4, PHP 5, PHP 7, PHP 8)

imagefontheight取得字型高度

說明

imagefontheight(GdFont|int $font): int

返回指定字型中字元的像素高度。

參數

font

可以是 1、2、3、4、5,表示 latin2 編碼中的內建字型(數字越大,字型越大),或是 imageloadfont() 返回的 GdFont 實例。

返回值

返回字型的像素高度。

更新日誌

版本 說明
8.1.0 現在 font 參數可以接受 GdFont 實例和 int 類型;先前只接受 int 類型。

範例

範例 #1 使用內建字型的 imagefontheight()

<?php
echo '字型高度:' . imagefontheight(4);
?>

上述範例將輸出類似以下的內容

Font height: 16

範例 #2 將 imagefontheight()imageloadfont() 搭配使用

<?php
// 載入 .gdf 字型
$font = imageloadfont('anonymous.gdf');

echo
'字型高度:' . imagefontheight($font);
?>

上述範例將輸出類似以下的內容

Font height: 43

另請參閱

新增註解

使用者貢獻的註解 1 則註解

1
dev at numist dot net
19 年前
這個函式庫函式對於僅包含文字的可變大小影像非常有用,就像我用來輸出累積錯誤訊息並在我的縮圖產生器中造成致命錯誤的函式一樣

<?php
function errimg($error) {
// $error is an array of error messages, each taking up one line
// initialization
$font_size = 2;
$text_width = imagefontwidth($font_size);
$text_height = imagefontheight($font_size);
$width = 0;
// the height of the image will be the number of items in $error
$height = count($error);

// this gets the length of the longest string, in characters to determine
// the width of the output image
for($x = 0; $x < count($error); $x++) {
if(
strlen($error[$x]) > $width) {
$width = strlen($error[$x]);
}
}

// next we turn the height and width into pixel values
$width = $width * $text_width;
$height = $height * $text_height;

// create image with dimensions to fit text, plus two extra rows and
// two extra columns for border
$im = imagecreatetruecolor($width + ( 2 * $text_width ),
$height + ( 2 * $text_height ) );
if(
$im) {
// image creation success
$text_color = imagecolorallocate($im, 233, 14, 91);
// this loop outputs the error message to the image
for($x = 0; $x < count($error); $x++) {
// imagestring(image, font, x, y, msg, color);
imagestring($im, $font_size, $text_width,
$text_height + $x * $text_height, $error[$x],
$text_color);
}
// now, render your image using your favorite image* function
// (imagejpeg, for instance)
out($im, array(), $error);
} else {
// image creation failed, so just dump the array along with extra error
$error[] = "Is GD Installed?";
die(
var_dump($error));
}
}
?>

該函式預期會傳入一個錯誤訊息陣列,然後輸出包含陣列內容的影像。如果您的程式碼包含在一個 HTML 頁面中,而如果影像無法正確渲染,該頁面將會顯示錯誤訊息,這將會特別有用。

此函式以影像形式顯示陣列,索引 0 位於頂部,最高索引位於底部。

不過,您必須自行撰寫 out() 函式,請參閱 imagejpeg、imagepng 等,以瞭解如何撰寫良好的輸出函式。
To Top