Générateur d'ASCII (Python)

2021

Script python, permettant de générer des fichiers textes ASCII à partir d’images.


from PIL import Image
import os
import time


CODE_LIB = r"-_#@%&/\|()[]?-_+~    "


count = len(CODE_LIB)
def transform_ascii(image_file): 
    image_file = image_file.convert("L") # convert image to gray
    code_pic = '' # result ASCII code
    for h in range(0,image_file.size[1]):
        for w in range(0,image_file.size[0]): 
            gray = image_file.getpixel((w,h))
            code_pic = code_pic + CODE_LIB[int(((count-1)*gray)/256)]
        code_pic = code_pic + "\n" 
    return code_pic

def convert_image():
    fn = input("input file name : ")
    hratio = float(input("input height zoom ratio(default 1.0) : ") or "1.0")
    wratio = float(input("input width zoom ratio(default 1.0) : ") or "1.0")
    image_file = Image.open(fn)
    image_file=image_file.resize((int(image_file.size[0]*wratio), int(image_file.size[1]*hratio)))
    print(u'Size info:',image_file.size[0],' ',image_file.size[1],' ')
    fo = open('foule.txt','w')
    trans_data = transform_ascii(image_file)
    print(trans_data)
    fo.write(trans_data)
    fo.close()

convert_image()

Autres projets