<?php
$bg_url = '1.png'; // 替换成你所指定的背景图片 URL，只能png，不知道为啥
// 加载背景图片
$bg_img = imagecreatefrompng($bg_url);

//$textFile = 'http://api.nanxi.asia:90/API/dujitang/api.php';
//文件或网站
$font = 'NiXiangShiWoDeAiQing-2.ttf';
//字体样式
$fontSize = 40;

$text=$_GET['text'];
//$text = "";
//文本
// 打开文本文件，读取内容并随机选择一条
if ($handle = fopen($textFile, 'r')) {
    $lines = file($textFile);
    $text = $lines[rand(0, count($lines) - 1)];
    fclose($handle);
}

$lines = autoSplitText($text, $fontSize, $font, imagesx($bg_img) - 40, 18); //40上下距离 左右18字
$startY = 99;
foreach ($lines as $line) {
    //$color = imagecolorallocate($bg_img, rand(0, 255), rand(0, 255), rand(0, 255));
    //随机颜色
    imagettftext($bg_img, $fontSize, -0.5, 70, $startY, $color, $font, $line);
    $startY += 50;
}

// 自动换行算法
function autoSplitText($str, $fontSize, $fontFile, $maxWidth, $maxCharsPerLine) {
    $lines = array('');
    $i = 0;
    $len = 0;

    $chars = preg_split('/(?<!^)(?!$)/u', $str);
    foreach ($chars as $char) {
        $box = imagettfbbox($fontSize, 0, $fontFile, $char);
        $charWidth = $box[2] - $box[0];
        $len += $charWidth;

        if ($char === "\n" || $len > $maxWidth || mb_strlen($lines[$i]) >= $maxCharsPerLine) {
            $i++;
            $lines[$i] = '';
            $len = $charWidth;
        }

        if ($char !== "\n") {
            $lines[$i] .= $char;
        }
    }

    return $lines;
}

      ob_clean();
      header('Content-Type: image/png');
      imagejpeg($bg_img, null, 100);
      imagedestroy($bg_img);
?>