使用 GD 庫讀取圖片像素,將每個像素的 RGB 值映射為帶顏色樣式的 <span>#</span>,透過極小字體與行高在瀏覽器還原圖像輪廓。
<html>
<head><title>Image to ASCII</title>
<style> body { line-height: 0; font-size: 1px; } </style>
</head>
<body>
<?php
$imagePath = 'image.jpg'; // 支援 HTTP/HTTPS 若 allow_url_fopen=On
$raw = file_get_contents($imagePath);
$img = imagecreatefromstring($raw);
$w = imagesx($img);
$h = imagesy($img);
for ($y = 0; $y < $h; $y++) {
for ($x = 0; $x < $w; $x++) {
$rgb = imagecolorat($img, $x, $y);
$a = ($rgb >> 24) & 0xFF;
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
$alpha = $a ? round(1 - $a / 255, 2) : 1; // 透明度反轉
if ($x === $w - 1) {
echo "<br>";
} else {
echo "<span style='color:rgba($r,$g,$b,$alpha);'>#</span>";
}
}
}
?>
</body></html>
imagescale($img, 200) 縮小至寬 200px 再處理。@%#*+=-:. 灰階字元集,配合單色字體更清晰。\033[38;2;R;G;Bm)。