from PIL import Image asciichar = list(“$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/|()1{}[]?-+~<>i!lI;:,”^`‘. “)WIDTH = 85 # 字符画的宽 HEIGHT = 25 # 字符画的高
讯享网# 将256灰度映射到70个字符上,也就是RGB值转字符的函数: def get_char(r, g, b, alpha=256): # alpha透明度 if alpha == 0:讯享网</span><span style="color: rgba(0, 0, 255, 1)">return</span> <span style="color: rgba(128, 0, 0, 1)">'</span> <span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">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 = ’https://www.cnblogs.com/gjq168/p/15.jpg‘ # 图片所在位置 im = Image.open(img) im = im.resize((WIDTH, HEIGHT), Image.NEAREST) txt = ”” for i in range(HEIGHT):</span><span style="color: rgba(0, 0, 255, 1)">for</span> j <span style="color: rgba(0, 0, 255, 1)">in</span><span style="color: rgba(0, 0, 0, 1)"> range(WIDTH): txt </span>+= get_char(*im.getpixel((j, i))) <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> 获得相应的字符</span> txt += <span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">’ print(txt) # 打印出字符画 # 将字符画 写入文件中 with open(“15.txt”, ‘w’) as f:讯享网f.write(txt)</span></pre>
讯享网


版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/151373.html