银杏节画出属于你的银杏

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from PIL import Image 

ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1\{\}[]?-_+~<>i!lI;:\^,\"`." )

WIDTH = 60
HEIGHT = 45

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)]
if __name__ == '__main__':
img = 'D:\ForStudy\Desktop\壁纸\银杏.png' # 图片所在位置
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)))
txt += '\n'
print(txt)
with open("D:\ForStudy\Desktop\壁纸\银杏.txt", 'w') as f:
f.write(txt)

在这里插入图片描述
在这里插入图片描述