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

PHP 將圖片轉換為 ASCII 藝術字(彩色/字符版)

     編輯:PHP 綜合知識

利用 GD 庫讀取圖片像素,按亮度映射字符集或輸出彩色 HTML span,生成可在終端或網頁顯示的 ASCII 藝術字。支援縮放、字符密度調整、彩色輸出模式。

核心原理

  1. 載入圖片 → imagecreatetruecolor 縮放至固定寬(如 100px)
  2. 遍歷每像素:imagecolorat 取 RGB → 計算灰度 0.2126*R + 0.7152*G + 0.0722*B
  3. 灰度值映射字符集:$chars = "$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. "
  4. 輸出模式:
     字符版:直接拼接字符 + <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 級)適合大尺寸細節
  • 效能**:大圖先縮放再處理;彩色版輸出極大 HTML,建議限制寬度 ≤ 200px
  • 透明背景**:PNG 透明區域灰度為 0,可映射為空格或特定字符

擴展應用

  1. 動態生成驗證碼背景噪點字符
  2. 圖片壓縮預覽:極低分辨率 ASCII 版作為佔位圖
  3. 終端工具:結合 php -r 腳本實現 img2ascii filename 命令
  4. 藝術風格轉換:字符集換為 Emoji、方塊字符、盲文點陣等
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved