1 import argparse 2 from PIL import Image 3 4 def parse_param(): 5 parser = argparse.ArgumentParser() # 命令行输入参数处理 6 7 parser.add_argument("input_file") # 输入文件 8 parser.add_argument("out_file") # 输出文件 9 10 parser.add_argument("--width", type=int, default=50) # 输出字符画宽 11 parser.add_argument("--height", type=int, default=50) # 输出字符画高 12 13 args = parser.parse_args() # 获取参数 14 width, height, input_file, out_file = args.width, args.height, args.input_file, args.out_file 15 return width, height, input_file, out_file 16 17 def get_char(r, g, b, alpha=256): 18 ‘‘‘ 19 gray / 256 = x / len(ascii_chra) 20 21 ‘‘‘ 22 if alpha == 0: 23 return " " 24 gray = (2126 * r + 7152 * g + 722 * b)/10000 25 # 将256灰度映射到70个字符上 26 ascii_char = list("[email protected]%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`‘. ") 27 x = int((gray / (alpha + 1.0)) * len(ascii_char)) 28 return ascii_char[x] 29 30 def write_file(out_file_name, content): 31 with open(out_file_name, "w") as f: 32 f.write(content) 33 34 def main(file_name="test.jpg", width=80, height=80, out_file_name="out_file"): 35 text = "" 36 im = Image.open(file_name) 37 im = im.resize((width, height), Image.NEAREST) 38 for i in range(height): 39 for j in range(width): 40 content = im.getpixel((j, i)) 41 text += get_char(*content) 42 text += "\n" 43 print(text) 44 write_file(out_file_name, text) # 字符画出到文件 45 46 47 if __name__ == ‘__main__‘: 48 main() 49 50 51 52 图片测试: 53 http://labfile.oss.aliyuncs.com/courses/370/ascii_dora.png
待完善.......