You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PHP将文本文件内容生成两列等宽的图片?

实现PHP生成双列文本图片的修改方案

原代码:

<?php
//include new data
//require_once 'grab.php';

$filename = "result.txt";

function convert($path) {
    $lines = file($path);
    $newpath = substr($path, 0, -3) . 'png';
    $im = imagecreate(800, 20 * count($lines));
    //background//
    $red = imagecolorallocate($im, 178, 34, 34);
    //background//
    $white = imagecolorallocate($im, 255, 255, 255);
    //background//
    //$white = imagecolorallocate($im, 255, 255, 255);
    
            
        foreach($lines as $i => $line) {
        //unknown-leftMargin-lineSpace//
        imagestring($im, 12, 50, 20 * $i, trim($line), $white);
        
    }
    imagepng($im, $newpath);
    imagedestroy($im);
}

//chdir('C:\TOP-20');
convert($filename);
echo "<center><img src='result.png' height='auto' width='auto' alt='error'><br>";
?>

问题:当前代码仅能生成单列图片,如何修改实现将文本内容分为左右两列(例如左列10行、右列10行)的等宽图片?


修改后的代码(自动分配行数)

<?php
//include new data
//require_once 'grab.php';

$filename = "result.txt";

function convert($path) {
    $lines = file($path);
    $totalLines = count($lines);
    // 自动分配左右列行数,奇数行时左列多一行
    $leftColLines = ceil($totalLines / 2);
    $rightColLines = floor($totalLines / 2);
    
    $newpath = substr($path, 0, -3) . 'png';
    // 图片高度取左列行数对应的高度(左列行数最多)
    $im = imagecreate(800, 20 * $leftColLines);
    
    // 定义颜色
    $red = imagecolorallocate($im, 178, 34, 34);
    $white = imagecolorallocate($im, 255, 255, 255);
    
    // 绘制左列
    for ($i = 0; $i < $leftColLines; $i++) {
        if (isset($lines[$i])) {
            imagestring($im, 12, 50, 20 * $i, trim($lines[$i]), $white);
        }
    }
    
    // 绘制右列
    for ($i = 0; $i < $rightColLines; $i++) {
        $lineIndex = $leftColLines + $i;
        if (isset($lines[$lineIndex])) {
            // 右列x坐标设为450,和左列保持等宽+间距
            imagestring($im, 12, 450, 20 * $i, trim($lines[$lineIndex]), $white);
        }
    }
    
    imagepng($im, $newpath);
    imagedestroy($im);
}

//chdir('C:\TOP-20');
convert($filename);
echo "<center><img src='result.png' height='auto' width='auto' alt='error'><br>";
?>

关键修改说明

  1. 行数拆分:用ceil()和floor()自动分配左右列行数,保证奇数行时左列多一行,排版更整齐。
  2. 图片高度调整:不再基于总行数计算高度,改用左列最大行数,避免多余空白。
  3. 双列绘制逻辑:分两次循环分别绘制左右列,右列x坐标设为450,和左列的50位置保持等宽+间距,实现对称布局。
  4. 边界判断:增加isset()判断,避免数组越界问题。

固定左右列各10行的修改方式

如果需要强制左列10行、右列10行,只需替换行数计算部分:

// 固定左右列各10行
$leftColLines = 10;
$rightColLines = 10;
// 图片高度固定为200(20*10)
$im = imagecreate(800, 200);

注:如果文本总行数超过20,超出部分会被截断;不足20行时对应列留空。

内容的提问来源于stack exchange,提问作者MPG

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 00:13:26