Skip to content

Instantly share code, notes, and snippets.

@mr-katsini
Created October 19, 2018 20:37
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 mr-katsini/47e659a3afb96a8a93fe597947676601 to your computer and use it in GitHub Desktop.
Save mr-katsini/47e659a3afb96a8a93fe597947676601 to your computer and use it in GitHub Desktop.
Easily convert a JPEG image file to an ASCII text file
from PIL import Image
from bisect import bisect
def main():
gray_scale = {
8: '@',
7: '#',
6: '£',
5: '=',
4: '+',
3: '|',
2: ':',
1: '.',
0: ' ',
}
bounds = [
32, 64, 96, 128, 160, 192, 224
]
scale = 1 # Defined here to tmake pixel scale
jpeg = Image.open('input.jpg')
jpeg.convert(mode='L')
loaded_jpg = jpeg.load()
txt = ""
file_name = "out.txt"
w = jpeg.size[0]
h = jpeg.size[1]
with open(file_name, 'w') as file:
for i in range(0, h):
if i % scale == 0:
for j in range(0, w):
if j % scale == 0:
brightness = loaded_jpg[j, i]
brightness = 250 - brightness[0]
index = bisect(bounds, brightness)
char = gray_scale[index]
txt = "{}{}".format(txt, char)
txt = "{}\n".format(txt)
file.write(txt)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment