<?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() 释放资源。