這個函式庫函式對於僅包含文字的可變大小影像非常有用,就像我用來輸出累積錯誤訊息並在我的縮圖產生器中造成致命錯誤的函式一樣
<?php
function errimg($error) {
$font_size = 2;
$text_width = imagefontwidth($font_size);
$text_height = imagefontheight($font_size);
$width = 0;
$height = count($error);
for($x = 0; $x < count($error); $x++) {
if(strlen($error[$x]) > $width) {
$width = strlen($error[$x]);
}
}
$width = $width * $text_width;
$height = $height * $text_height;
$im = imagecreatetruecolor($width + ( 2 * $text_width ),
$height + ( 2 * $text_height ) );
if($im) {
$text_color = imagecolorallocate($im, 233, 14, 91);
for($x = 0; $x < count($error); $x++) {
imagestring($im, $font_size, $text_width,
$text_height + $x * $text_height, $error[$x],
$text_color);
}
out($im, array(), $error);
} else {
$error[] = "Is GD Installed?";
die(var_dump($error));
}
}
?>
該函式預期會傳入一個錯誤訊息陣列,然後輸出包含陣列內容的影像。如果您的程式碼包含在一個 HTML 頁面中,而如果影像無法正確渲染,該頁面將會顯示錯誤訊息,這將會特別有用。
此函式以影像形式顯示陣列,索引 0 位於頂部,最高索引位於底部。
不過,您必須自行撰寫 out() 函式,請參閱 imagejpeg、imagepng 等,以瞭解如何撰寫良好的輸出函式。