Skip to content

Instantly share code, notes, and snippets.

@natematias
Created April 27, 2019 01:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save natematias/59a6aa45dbf49abf2e4a963a8c5dd6d6 to your computer and use it in GitHub Desktop.
Save natematias/59a6aa45dbf49abf2e4a963a8c5dd6d6 to your computer and use it in GitHub Desktop.
from PIL import Image
import sys
## Example via: https://stackoverflow.com/questions/28057722/algorithm-to-turn-a-large-blob-of-text-into-an-image-as-defined-by-the-image-e
def to_ascii(img,maxLen=250.0):
#resize to maximum line length
width, height = img.size
rate = maxLen / max(width, height)
width = int(rate * width) # cast to int
height = int(rate * height)
img_small = img.resize((width, height))
pixels = img_small.load()
string = ""
for h in range(height):
for w in range(width):
rgb = pixels[w, h]
if rgb == 0:
string += ' '
else:
string += '#'
string += "\n"
return string
def hashes_to_text(hash_art, text):
output = list(hash_art)
tidx = 0
for idx, char in enumerate(hash_art):
if char == '#':
output[idx] = text[tidx%len(text)]
tidx += 1
return ''.join(output)
image_file = Image.open(sys.argv[1])
image_file = image_file.convert('1') # to black/white
W = to_ascii(image_file)
W = hashes_to_text(W,open(sys.argv[2], "r").read())
print(W)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment