银杏节画出属于你的银杏

银杏节画出属于你的银杏

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)

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

猜你喜欢

转载自blog.csdn.net/QinZheng7575/article/details/110354835