Connecting Tech Pros Worldwide Help | Site Map

ascii art creator

kudos's Avatar
Expert
 
Join Date: Jul 2006
Location: Norway
Posts: 108
#1   Sep 14 '09
Do you remeber the "old" internet? before webbrowsers, when everything had a strong unix flavour? Back then there was something called "ascii art" that is, use the ascii letters to create an image. Here is a program that takes an image (640x384) and converts it to ascii strings. I wanted to create this image for a t-shirt

You would need to copy the "courier new" font from your font directory to the same directory as the script, and also add an image that should be converted:

Expand|Select|Wrap|Line Numbers
  1. import Image, ImageDraw
  2. import ImageFont
  3. import math
  4.  
  5. # funny useless program
  6.  
  7. lu = []
  8. for i in range(125-32):
  9.  lu.append(chr(i+33))
  10. i2 = Image.new("RGBA",(64,64))
  11. ii = Image.open("mona.png") # change this to your own picture, but it needs to be 640x384!
  12. im = Image.new("RGBA",(64,64))
  13. d = ImageDraw.Draw(im)
  14. f = ImageFont.truetype("courbi.ttf",13)
  15.  
  16. str=""
  17. for v in range(24):
  18.  print v
  19.  for k in range(80):
  20.   chr = ""
  21.   maxdiff = 0xffffff
  22.   for e in lu:
  23.    d.rectangle([0,0,64,64], fill=0)
  24.    d.text((0,0),e,font=f,fill=0xffffff)
  25.    diff = 0
  26.    r0 = 0
  27.    g0 = 0
  28.    b0 = 0
  29.    for a in range(16):
  30.     for b in range(8):
  31.      c =  im.getpixel((b,a))[0]
  32.      c0 = (ii.getpixel((b+(k*8),a+(v*16)))[0] + ii.getpixel((b+(k*8),a+(v*16)))[1] + ii.getpixel((b+(k*8),a+(v*16)))[2])/3.0
  33.      r0+= ii.getpixel((b+(k*8),a+(v*16)))[0]
  34.      g0+= ii.getpixel((b+(k*8),a+(v*16)))[1]
  35.      b0+= ii.getpixel((b+(k*8),a+(v*16)))[2]
  36.  
  37.      diff+=abs(c-c0)
  38.    if(diff < maxdiff):
  39.     maxdiff = diff
  40.     chr = e
  41.  
  42.   r0*=1.0
  43.   g0*=1.0
  44.   b0*=1.0
  45.   r0/=(16.0*8.0)
  46.   g0/=(16.0*8.0)
  47.   b0/=(16.0*8.0)
  48.   ir0 = int(r0)
  49.   ig0 = int(g0)
  50.   ib0 = int(b0)
  51.  
  52.   r1 =  hex(ir0)
  53.   r1 = r1[2:len(r1)]
  54.   g1 = hex(ig0)
  55.   g1 = g1[2:len(g1)]
  56.   b1 = hex(ib0)
  57.   b1 = b1[2:len(g1)]
  58.  
  59.   if(chr == " "):
  60.    chr="&nbsp;"
  61.  
  62.   str+="<td width=\"8px\"><font size=\"1px\" color=\"#"+r1+g1+b1+"\">"+chr+"</font></td>"
  63.  str="<tr>"+str+"</tr>"
  64.  
  65. str= "<html><body bgcolor=\"#000000\"><table width=\"640px\" height=\"386px\">"+str+"</table></body></html>"
  66. f = open("mona.txt","w")
  67. f.write(str)
  68. f.close()
  69.  
This program output it as a .html file, but it should easy to modify so it will output txt instead.

-kudos



Reply