Damn Simple PHP ASCII ART Generator — Donat Studios
source link: https://donatstudios.com/Damn-Simple-PHP-ASCII-Art-Generator
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Damn Simple PHP ASCII Art Generator
So yesterday I was bored and asked my friend what I should do. She replied "I don't know, draw ASCII art or something!" and sitting there with the terminal open I kind of wondered what it would take to write one of those image to ASCII scripts.
20 minutes later I had the following PHP Shell Script! It works by simply sampling the saturation of every Xth pixel and mapping that saturation to a character from an array. There is no nearest-neighboring or anything like that, just straight up sampling.
#!/usr/bin/php -q <?php
if(isset($argv[1]) && strlen($argv[1])) { $file = $argv[1]; }else{ echo 'Please Specify a File'; exit(1); }
$img = imagecreatefromstring(file_get_contents($file)); list($width, $height) = getimagesize($file);
$scale = 10;
$chars = array( ' ', '\'', '.', ':', '|', 'T', 'X', '0', '#', );
$chars = array_reverse($chars);
$c_count = count($chars);
for($y = 0; $y <= $height - $scale - 1; $y += $scale) { for($x = 0; $x <= $width - ($scale / 2) - 1; $x += ($scale / 2)) { $rgb = imagecolorat($img, $x, $y); $r = (($rgb >> 16) & 0xFF); $g = (($rgb >> 8) & 0xFF); $b = ($rgb & 0xFF); $sat = ($r + $g + $b) / (255 * 3); echo $chars[ (int)( $sat * ($c_count - 1) ) ]; } echo PHP_EOL; }
Huzzah!
And there you have it! A whopping 35 lines of code. There is a ton of tweaking you can do like changing the array of characters, or adjusting the $scale variable which is simply how wide of a sample it makes. Setting it to 1 for instance should sample every pixel on the Y and every other pixel on the X (so it scales propperly). To the right is a sample output of the script.
Do You Trust Me?
The script accepts local or remote image paths as the first argument. The following is a simple usage example you can use to get you started.
./ascii.php "http://donatstudios.com/images/site/JesseDonat.jpg"
It was a fun little project and I look forward to seeing if/what the internet comes up with for it. Fork me on Github, or post links in the comments! Happy hacking!
Comment by: A Name on Apr. 10, 2013
Comment by: cyan on May. 3, 2013
Comment by: cyan on May. 3, 2013
Comment by: oguzhan on Sep. 19, 2014
Comment by: Evan Toder on Feb. 23, 2017
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK