[分享] 圖片轉ASCII
<?php
$filename = 'JPEGFile.jpg';
//載入JPEG圖片檔
$image = imagecreatefromjpeg($filename);
//取得圖片的長度及寬度
list($width, $height) = getimagesize($filename);
//ASCII由左至右分別對應圖片顏色的深至淺
$ascii = array('@', '&', '$', 'B', 'P', 'O', 'X', 'a', 'o', 'x', ':', ',', '.', ' ');
$count = count($ascii);
for ($y = 0; $y < $height; $y++)
{
for ($x = 0; $x < $width; $x++)
{
//掃描像素點
$image_index = imagecolorat($image, $x, $y);
$image_color = imagecolorsforindex($image, $image_index);
//取得像素點顏色
$r = $image_color['red'];
$g = $image_color['green'];
$b = $image_color['blue'];
$r2 = pow($r, 2);
$g2 = pow($g, 2);
$b2 = pow($b, 2);
$rgb = $r + $g + $b;
$rgb2 = $r2 + $g2 + $b2;
//避免除以零的狀況
if ($rgb == 0)
{
$rgb = 1;
}
//灰階化
$gray = floor($rgb2 / $rgb);
//取出像素顏色深淺對應的ASCII
$index = floor($gray / (256 / $count));
echo $ascii[$index];
}
echo "<br />\n";
}
//結束圖片
imagedestroy($image);
?>
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 220.228.89.76
推
09/04 10:30, , 1F
09/04 10:30, 1F
PHP 近期熱門文章
PTT數位生活區 即時熱門文章