文章目录

说实话,原本我也没想到做个字符画还能有续集。今天搜教程,看到了有彩色版的转换方式。有了之前两个教程的基础,既解决了基本的字符处理问题( 用Python将图片转为字符画 ),又解决了界面问题( 用Python实现简易计算器 ),这次的实践就是轻松加愉快了。

如果没有基础,可以看前面两篇了解一下,这次就直接上代码吧。

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
from PIL import Image, ImageFont, ImageDraw
from tkinter import filedialog, Tk

def open_path():
root = Tk()
root.withdraw()
file_path = (filedialog.askopenfilename(title='选择图片文件', filetypes=[('All Files', '*')]))
return file_path

print('请选择图片:')
IMG = open_path() # 图片路径
ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ")

print('正在转换......')

def get_char(r, g, b, alpha=256): # alpha透明度
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)]

def save_path():
# 保存图片路径
root = Tk()
root.withdraw()
file_path = (filedialog.asksaveasfilename(title='保存路径', filetypes=[('All Files', '*')]))
return file_path

if __name__ == '__main__':
img = Image.open(IMG)
WIDTH = int(img.width / 6)
HEIGHT = int(img.height / 15)
img_txt = Image.new("RGB", (img.width, img.height), (255, 255, 255))
img = img.resize((WIDTH, HEIGHT), Image.NEAREST)
txt = ""
colors = []
for i in range(HEIGHT):
for j in range(WIDTH):
pixel = img.getpixel((j, i))
colors.append((pixel[0], pixel[1], pixel[2])) # 记录像素颜色信息
if (len(pixel) == 4):
txt += get_char(pixel[0], pixel[1], pixel[2], pixel[3])
else:
txt += get_char(pixel[0], pixel[1], pixel[2])
txt += '\n'
colors.append((255, 255, 255))
dr = ImageDraw.Draw(img_txt)
font = ImageFont.load_default().font
x = y = 0
# 获取字体的宽高
font_w, font_h = font.getsize(txt[1])
font_h *= 1.37
# 为每个ascii进行上色
for i in range(len(txt)):
if (txt[i] == '\n'):
x += font_h
y = -font_w
dr.text([y, x], txt[i], colors[i])
y += font_w

print('转换成功!')
print('请选择保存路径:')
save_path = save_path()+'.png'
img_txt.save(save_path)
print('保存成功')
img = Image.open(save_path)
img.show()

原图片、完成图、细节图如下。

♦ 本文固定连接:https://www.gsgundam.com/archive/2022-07-12-how-to-draw-image-ascii-color-python-pil-tkinter/

♦ 转载请注明:GSGundam 2022年07月12日发布于 GSGUNDAM砍柴工

♦ 本文版权归作者,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接。

♦ 原创不易,如果页面上有适合你的广告,不妨点击一下看看,支持作者。(广告来源:Google Adsense)

♦ 本文总阅读量