Skip to content

Instantly share code, notes, and snippets.

Last active August 29, 2015 14:06
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
from PIL import Image
from urllib.request import urlopen
from urllib.parse import quote_plus
import json
import io
import re
from random import choice
def first(xs):
for x in xs:
return x
def google_image_search(query):
urlquery = quote_plus(query)
url = '' % urlquery
req = urlopen(url)
txt ='utf-8')
res = json.loads(txt)
img_urls = map(lambda x: x['unescapedUrl'], res['responseData']['results'])
return list(img_urls)
def ascii_from_image(im, dims = (200, 54), chars = ['@', 'X', 'O', 'o', '+', ',', ' ']):
im = im.convert('L')
w, h = im.size
im = im.resize((int(w * 2), h))
chars = [(int(255 * (1+i) / len(chars)), c) for i, c in enumerate(chars)]
w, h = im.size
ascii = ''
for y in range(h):
for x in range(w):
v = im.getpixel((x, y))
char = first(filter(lambda w: w[0]>=v, chars))[1]
ascii += char
ascii += '\n'
return ascii
def image_from_url(url):
req = urlopen(url)
bytes =
import sys
if len(sys.argv) != 2:
print('Fetching results...')
urls = google_image_search(sys.argv[1])
url = choice(urls)
print('Image results = %d' % len(urls))
print('URL = %s' % url)
print('Downloading image...')
im = image_from_url(url)
ascii = ascii_from_image(im)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment