Skip to content

Instantly share code, notes, and snippets.

@Garciat
Last active August 29, 2015 14:06
Show Gist options
  • Save Garciat/73d411745ee1847446e5 to your computer and use it in GitHub Desktop.
Save Garciat/73d411745ee1847446e5 to your computer and use it in GitHub Desktop.
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 = 'https://ajax.googleapis.com/ajax/services/search/images?v=1.0&rsz=8&q=%s' % urlquery
req = urlopen(url)
txt = req.read().decode('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')
im.thumbnail(dims)
chars.reverse()
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 = req.read()
return Image.open(io.BytesIO(bytes))
import sys
if len(sys.argv) != 2:
exit(1)
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)
print(ascii)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment