PIL安装很麻烦,推荐下载exe直接安装
PIL官网:http://pythonware.com/products/pil/
但现在里面下载链接访问不了,我把32位和64位版本上传到博客园以供下载
PILwin32:http://files.cnblogs.com/files/pcat/PILwin32.zip
PILwin64:http://files.cnblogs.com/files/pcat/PILwin64.zip
#coding=utf-8 from PIL.Image import Image import argparse #命令行输入参数处理 parser=argparse.ArgumentParser() parser.add_argument('file') #输入文件 parser.add_argument('-o','--output') parser.add_argument('--width',type=int,default=80) parser.add_argument('--heigth',type=int,default=80) args=parser.parse_args() IMG=args.file WIDTH=args.width HEIGHT=args.heigth OUTPUT=args.output ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/|()1{}[]?-_+~<>i!lI;:,"^`'. ") #将256灰度映射到70个字符上 def get_char(r,g,b,alpha=256): if alpha==0: return ' ' length=len(ascii_char) gray=int(0.2126 * r + 0.7152 * g + 0.0722 * b) unit=(256.0+1)/length return ascii_char[int(gray/unit)] im = Image.open(IMG) im = im.resize((WIDTH,HEIGHT), Image.NEAREST) txt="" for i in range(HEIGHT): for j in range(WIDTH): txt+=get_char(*im.getpixel((j,i))) print txt #字符画输出文件 if OUTPUT: with open(OUTPUT,'w') as f: f.write(txt) else: with open("output.txt",'w') as f: f.write(txt)
链接:https://www.shiyanlou.com/courses/370/labs/1191/document