ASCII Art converter resampled
- Tim Brockman
- @ 4:37 am
In an earlier post I wrote a some quick code to convert simple gif images to ASCII Art using PHP GD functions. In case you didn't notice, things get distorted because pixels are square however ASCII symbols are rectangular and have spacing between each line. In my measurements this is about 8x11 (Width x Height) which means we need to squish the image to about 70% of its original height before turning it into ASCII art. (after further testing 66% looked better to me)
In order to do this we can use one of 2 functions, ImageCopyResized() or ImageCopyResampled(). For this the latter, tends to be cleaner but slower, so I'll use that. I'll also need ImageCreateTrueColor() to create the image to become the resampled copy's destination.
So here's the new code created from the old code.
giftoascii_resampled.php
<?
// displays gif as ascii art
$raw_image = imagecreatefromgif("images/dobbshead.gif");
$xlimit = imagesx($raw_image);
$raw_height = imagesy($raw_image);
$ylimit = floor($raw_height * 0.7); // or 0.66
$the_image = imagecreatetruecolor($xlimit, $ylimit);
imagecopyresampled($the_image, $raw_image, 0, 0, 0, 0, $xlimit, $ylimit, $xlimit, $raw_height);
print("<tt>\n");
for($ycurrent=0; $ycurrent < $ylimit; $ycurrent++){
for($xcurrent=0; $xcurrent < $xlimit; $xcurrent++){
$current_color = imagecolorat($the_image, $xcurrent, $ycurrent);
$rgb = imagecolorsforindex($the_image, $current_color);
$color_score = $rgb['red'] + $rgb['green'] + $rgb['blue'];
if($color_score < 300){
//black color
print("M");
}elseif($color_score > 600){
//white color
print(" ");
}else{
//gray color
print("$");
}
// print($color_score);
}
print("<br />\n");
}
print("</tt>\n");
imagedestroy($the_image);
imagedestroy($raw_image);
?>
Don't forget to add the second imagedestroy.
This can be seen in action here --> Resampled gif to ASCII art with PHP GD
and compared to the original version here --> gif to ASCII
Now that the code is modified to display images in proportion it is more appropriate for designs where proper geometry is more important like type or logos.
L. A. County Coroner’s Office downplayed the leaking of some anomalous findings in Michael Jackson’s yet unreleased autopsy. Genetic sampling and testing done to facilitate the upcoming custody war revealed some shocking results. According to an unnamed source within the Los Angeles County Coroner’s office, genetic samples taken from Michael Jackson’s body show signs of …continue reading…
My personal fondness for ASCII art began on the BSU VAX/VMS terminals back in 1993. I found a sweet Spock portrait to append to my login script. It made me smile with crazy nerdmusment every time I logged into the account. As any good subgenius, I’ll start with the Dobbshead. This is small, only 66×100 …continue reading…
Contact PHÓ