利用 GD 庫讀取圖片像素,按亮度映射字符集或輸出彩色 HTML span,生成可在終端或網頁顯示的 ASCII 藝術字。支援縮放、字符密度調整、彩色輸出模式。
imagecreatetruecolor 縮放至固定寬(如 100px)imagecolorat 取 RGB → 計算灰度 0.2126*R + 0.7152*G + 0.0722*B$chars = "$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. "<br><span style="color:rgb(r,g,b)"><?php
$file = 'd:\\ascii_dora.png';
$chars = "$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\\|()1{}[]?-_+~<>i!lI;:,\"^`'. ";
function getChar($rgba, $chars) {
$gray = intval(0.2126 * $rgba['red'] + 0.7152 * $rgba['green'] + 0.0722 * $rgba['blue']);
if ($gray == 0) return '.';
if ($gray < 196) {
$unit = 257 / strlen($chars);
return $chars[intval($gray / $unit)];
}
return ' ';
}
function getColorSpan($rgba, $chars) {
$rand = rand(0, strlen($chars)-1);
return '<span style="color:rgb('.$rgba['red'].','.$rgba['green'].','.$rgba['blue'].')">'.$chars[$rand].'</span>';
}
function resizeImg($file, $newH = 100) {
list($w, $h, $type) = getimagesize($file);
$func = 'imagecreatefrom' . image_type_to_extension($type, false);
$src = $func($file);
$newW = $w * $newH / $h;
$dst = imagecreatetruecolor($newW, $newH);
imagecopyresampled($dst, $src, 0,0, 0,0, $newW, $newH, $w, $h);
return $dst;
}
$im = resizeImg($file);
$w = imagesx($im); $h = imagesy($im);
echo '<pre style="font-size:4px;line-height:1.2">';
for ($y = 0; $y < $h; $y++) {
for ($x = 0; $x < $w; $x++) {
$rgb = imagecolorsforindex($im, imagecolorat($im, $x, $y));
// 切換這裡:getChar($rgb, $chars) 字符版 | getColorSpan($rgb, $chars) 彩色版
echo getColorSpan($rgb, $chars);
}
echo "<br>";
}
echo '</pre>';
| 模式 | 適用場景 | 體積 |
|---|---|---|
| 字符版(單色) | 終端輸出、純文本郵件、代碼註釋 | 極小 |
| 彩色 HTML 版 | 網頁展示、藝術效果、個人主頁 | 較大(每像素一 span) |
$newH 控制寬度,配合 CSS font-size、line-height 微調@%#*+=-:. (10 級)適合小尺寸;$chars(70 級)適合大尺寸細節php -r 腳本實現 img2ascii filename 命令