首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 生成 ASCII 藝術字:從圖片到字符畫的完整實現

     編輯:PHP 綜合知識

效果預覽

在線演示:https://www.healdream.com/upload/html/test_ascii.html
(PHP 動態生成的 BI Logo 字符畫,效果清晰可辨)

核心原理

  1. 圖片讀取:使用 GD 库(imagecreatefromjpeg/png/gif)載入目標圖片。
  2. 灰度化:遍歷像素,按 0.299*R + 0.587*G + 0.114*B 計算亮度值(0-255)。
  3. 縮放適配:根據終端寬度/字符寬高比(約 1:2)縮放圖片,避免字符畫過寬或變形。
  4. 字符映射:將 0-255 亮度映射到有序字符集,如 $chars = "@%#*+=-:. "(從深到淺)。
  5. 輸出:拼接字符並換行,輸出 <pre> 標籤保持等寬顯示。

完整 PHP 實現(可直接保存為 ascii_art.php)

<?php
/**
 * 圖片轉 ASCII 藝術字
 * @param string $imagePath 圖片路徑或 URL
 * @param int    $width     輸出字符寬度(列數)
 * @param string $charset   字符集(深->淺)
 * @return string           包含 <pre> 標籤的 HTML 片段
 */
function imageToAscii($imagePath, $width = 120, $charset = "@%#*+=-:. ")
{
    // 1. 載入圖片(支持遠程 URL,需 allow_url_fopen)
    $src = @imagecreatefromstring(file_get_contents($imagePath));
    if (!$src) {
        return "<p style='color:red'>圖片載入失敗:{$imagePath}</p>";
    }

    // 2. 計算縮放比例(字符高寬比約 2:1)
    $origW = imagesx($src);
    $origH = imagesy($src);
    $height = (int)($width * $origH / $origW / 2); // 除 2 修正字符高寬比
    $height = max(1, $height);

    // 3. 創建縮放後的真彩色圖片
    $dst = imagecreatetruecolor($width, $height);
    imagecopyresampled($dst, $src, 0, 0, 0, 0, $width, $height, $origW, $origH);
    imagedestroy($src);

    // 4. 灰度映射
    $len = strlen($charset) - 1;
    $output = "<pre style='font-size:4px;line-height:1.1;margin:0;font-family:monospace;'>";

    for ($y = 0; $y < $height; $y++) {
        for ($x = 0; $x < $width; $x++) {
            $rgb = imagecolorat($dst, $x, $y);
            $r = ($rgb >> 16) & 0xFF;
            $g = ($rgb >> 8) & 0xFF;
            $b = $rgb & 0xFF;
            $gray = (int)(0.299 * $r + 0.587 * $g + 0.114 * $b);
            $index = (int)($gray / 255 * $len);
            $output .= $charset[$index];
        }
        $output .= "\n";
    }
    $output .= "</pre>";
    imagedestroy($dst);
    return $output;
}

// ===== 使用示例 =====
header('Content-Type: text/html; charset=utf-8');
// 本地圖片
echo imageToAscii('./logo.png', 160);
// 或遠程圖片
// echo imageToAscii('https://example.com/avatar.jpg', 100);
?>

進階優化方向

優化點方案收益
字符集選擇根據輸出場景調整:終端用 @%#*+=-:. ,網頁可用更豐富 Unicode 區塊字符(如 █▓▒░)視覺層次更豐富
色彩保留輸出 <span style="color:rgb(r,g,b)">█</span>,保留原圖色彩彩色字符畫
性能加速使用 imagefilter($dst, IMG_FILTER_GRAYSCALE) 一鍵灰度,避免雙層循環逐像素計算大圖處理提速 5-10 倍
CLI 直接輸出去掉 HTML 標籤,直接 echo 字符 + PHP_EOL,配合 fwrite(STDOUT, ...)終端動畫、日誌裝飾
視頻轉字符動畫ffmpeg -i input.mp4 -vf fps=10 frame_%04d.png 幀拆解 → 批量轉 ASCII → 終端逐幀播放Bad Apple!! 字符版

源碼下載

原作者提供的完整源碼包(含演示頁面):
https://www.51files.com/?GKGY4UWEK68EGCQS0MEZ

總結

PHP 配合 GD 库實現圖片轉 ASCII 藝術字,核心邏輯不足 50 行,卻能產出極具極客美感的視覺效果。無論是作為登錄頁背景、API 文檔裝飾、還是 CLI 工具的彩蛋,這都是一個「低成本、高趣味」的實用技能。建議將上述函數封裝為 Composer 包(vendor/ascii-art),並在項目中複用。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved