过年前,在知乎上看到有一些字符画,想起以前看到用python很容易实现字符画的转换,所以自己摸索了一番,python真的太强大了,几条语句就搞定了。
Python字符画转换主要适用了PIL这个插件(可将彩色图片转为灰阶图片,每个灰阶转为对应字符),可以使用PIP命令安装插件。
pip install pillow
在新文件夹下,建立如下python源文件,文件名任意。
# coding=utf-8
from PIL import Image
char_arr = list("#$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'.")
im = Image.open("profile.png")
im = im.convert("RGBA")
txt = ""
def get_char(r, g, b, alpha):
if alpha == 0:
return " "
gray = 0.2126 * r + 0.7152 * g + 0.0722 * b
unit = (256.0 + 1) / len(char_arr)
return char_arr[int(gray / unit)]
f=open("test.txt","w")
for i in range(im.height):
for j in range(im.width):
txt += get_char(*im.getpixel((j, i)))
txt += "\n"
print(txt)
f.write(txt)
f.close()
然后,将所需转换的图片复制到该文件夹下,图片名字 "profile.png",与程序对应(注意控制图片像素,每个像素对应一个字符!)。
本例中,我将图片最终转换的字符画转存到本地的 test.txt 文件中,方便转贴发表。
通过以上例子,大家可以充分发挥想象,可以打印“情侣合照”、“大头贴”等等,为生活增添一点乐趣。