<?php
// 设置内容类型为图像
header('Content-Type: image/png');
// 创建画布
$width = 800;
$height = 100;
$image = imagecreatetruecolor($width, $height);
// 定义颜色
$backgroundColor = imagecolorallocate($image, 0, 0, 0); // 黑色背景
$textColor = imagecolorallocate($image, 255, 255, 255); // 白色文字
// 填充背景
imagefilledrectangle($image, 0, 0, $width, $height, $backgroundColor);
// 要显示的弹幕文字
$danmuTexts = [
"欢迎来到m66.net!",
"PHP制作弹幕图层演示",
"让文字飞一会儿~"
];
// 使用内置字体编号(1-5)
$font = 5;
// 获取字体的宽度与高度
$charWidth = imagefontwidth($font);
$charHeight = imagefontheight($font);
// 初始Y位置
$y = 10;
// 循环绘制每条弹幕
foreach ($danmuTexts as $index => $text) {
// 计算文字总宽度
$textWidth = strlen($text) * $charWidth;
// 设置X位置为图像右侧外边界,用于模拟从右向左滚动
$x = $width - ($index * 50); // 模拟不同起始偏移
// Y位置随行数递增
$textY = $y + $index * ($charHeight + 5);
// 绘制文字
imagestring($image, $font, $x, $textY, $text, $textColor);
}
// 输出图像
imagepng($image);
imagedestroy($image);
?>
使用imagecreatetruecolor()創建一個指定寬高的空白畫布。
設置顏色:
利用imagecolorallocate()為背景與文字分別分配顏色值。
填充背景色:
使用imagefilledrectangle()將整個圖層填充為黑色,模擬常見的彈幕背景。
設置文字內容與字體:
定義要展示的幾段文字,選擇PHP 內置字體(編號1-5)。如果你使用的是imagettftext()也可以支持自定義TTF 字體文件。
計算文字寬度:
imagefontwidth()返回的是當前字體每個字符的像素寬度,結合strlen()可以算出整段文字所需寬度。
繪製文字:
imagestring()用來繪製文字,將它放置在畫布的合適位置上。我們設置了不同的X 偏移,模擬彈幕從右側進入的效果。
輸出圖像並銷毀資源:
用imagepng()輸出PNG 圖片,之後使用imagedestroy()釋放資源。