在線演示:https://www.healdream.com/upload/html/test_ascii.html
(PHP 動態生成的 BI Logo 字符畫,效果清晰可辨)
imagecreatefromjpeg/png/gif)載入目標圖片。0.299*R + 0.587*G + 0.114*B 計算亮度值(0-255)。$chars = "@%#*+=-:. "(從深到淺)。<pre> 標籤保持等寬顯示。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),並在項目中複用。