PIL(Python Image Library)库是Python平台上一个功能强大的图像处理标准库,支持图像的存储、显示和处理,几乎可以处理所有图片格式,如图像的压缩、裁剪、叠加、添加文字等等。
安装PIL库:pip install pillow
from PIL import Image ascii_char=list('\~!@#.,[abcdefghij]wmnoxy$%;-=<>?:|^&*/ ') def get_char(r,b,g,alpha=256):if alpha==0:return ' 'gray=int(0.2126*r+0.7125*g+0.0722*b)uint=256/len(ascii_char)return ascii_char[int(gray/uint)] def run():img=Image.open('0.jpg')WIDTH,HEIGHT=100,60img=img.resize((WIDTH,HEIGHT))txt=""for i in range(HEIGHT):for j in range(WIDTH):txt+=get_char(*img.getpixel((j,i)))txt+='\n'with open("pic.txt",'w') as fo:fo.write(txt)print(txt) run()
示例