PHP Script To Turn Image Into ASCII Text

Monday, October 6, 2008 - 13:59

Use the following snippet to convert any jpeg image into the equivalent image in ASCII format. It works by loading an image using the PHP GD2 library function ImageCreateFromJpeg() and then figures out the height and width of it. It then uses these values to loop through every pixel in the image and figures out the colour of that pixel. It uses this value to create a <span> element that uses the text colour of a # to change the colour of the text.

An additional time (and space) saver for this function is that it detects any pixels that are just off white and simply displays a &nbsp; character instead.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
$img = ImageCreateFromJpeg('logo.jpg');
 
// get height and with of the image.
$width = imagesx($img);
$height = imagesy($img);
 
echo '<pre style="font-size:1px;">';
for($h=0;$h<$height;$h++){
 for($w=0;$w<=$width;$w++){
  if($w == $width){
   echo '<br>';
   continue;
  }
  // get image at pixel location
  $rgb = ImageColorAt($img, $w, $h);
  // convert colour into usable format
  $r = ($rgb >> 16) & 0xFF;
  $g = ($rgb >> 8 ) & 0xFF;
  $b = $rgb & 0xFF;
  // check for white/off-white colour
  if($r > 200 && $g > 200 && $b > 200){
   echo '&nbsp';
  }else{
   echo '<span  style="color:rgb('.$r.','.$g.','.$b.');">#</span>';
  }
 }
}
echo '
';

As an example, take the following, quite recognisable, image.

This is transformed into the text on the following page.

The Google logo in ASCII format

Beware that although this works will for small image sizes if you try to convert a very large image you will find that the script takes a long time. This is because it looks at every pixel in turn and converts the colour into something usable, so if there are a lot of pixels it takes a long time to look at every one. Not only this, but you will also find that the size of the page generated will grow significantly due to all of the span elements being created.

Category: 
philipnorton42's picture

Philip Norton

Phil is the founder and administrator of #! code and is an IT professional working in the North West of the UK.
Google+ | Twitter

Comments

philipnorton42's picture
Submitted by philipnorton42 on Thu, 04/17/2014 - 09:12

You need some form of OCR library. The last time I looked there wasn't a good PHP library to do this, but things may have progressed.

Add new comment