[分享] 圖片轉ASCII

看板PHP作者 (HKC === KFC //false)時間17年前 (2008/08/31 01:11), 編輯推噓1(100)
留言1則, 1人參與, 最新討論串1/1
<?php $filename = 'JPEGFile.jpg'; //載入JPEG圖片檔 $image = imagecreatefromjpeg($filename); //取得圖片的長度及寬度 list($width, $height) = getimagesize($filename); //ASCII由左至右分別對應圖片顏色的深至淺 $ascii = array('@', '&', '$', 'B', 'P', 'O', 'X', 'a', 'o', 'x', ':', ',', '.', '&nbsp;'); $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
文章代碼(AID): #18kNyhBH (PHP)
文章代碼(AID): #18kNyhBH (PHP)