Skip to content

Commit 797574b

Browse files
committed
add code
1 parent 3267a89 commit 797574b

File tree

4 files changed

+31
-0
lines changed

4 files changed

+31
-0
lines changed
8.88 MB
Binary file not shown.

doudou/2021-09-08-text-img/app.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# coding:utf-8
2+
3+
from PIL import Image, ImageDraw, ImageFont
4+
5+
img_child_size = 15
6+
text = "今晚的月色真美"
7+
font = ImageFont.truetype('AliPuHui-Bold.ttf', img_child_size)
8+
img_path = './moon.png'
9+
10+
img = Image.open(img_path)
11+
img_w, img_h = img.size
12+
img_child = Image.new("RGB", (img_child_size, img_child_size))
13+
img_ans = Image.new("RGB", (img_child_size * img_w, img_child_size * img_h))
14+
15+
text_w, text_h = font.getsize("中") # 获单个文字的宽、高
16+
offset_x = (img_child_size - text_w) >> 1 # 文字水平居中
17+
offset_y = (img_child_size - text_h) >> 1 # 文字垂直居中
18+
19+
char_index = 0
20+
draw = ImageDraw.Draw(img_child) # 小图的绘图对象,用于绘制文字
21+
22+
for x in range(img_w): # 宽在外 高在内,因此文字的方向是从左到右,从上到下排列的
23+
for y in range(img_h):
24+
draw.rectangle((0, 0, img_child_size, img_child_size), fill='lightgray') # 绘制背景,看起来会好一些
25+
draw.text((offset_x, offset_y), text[char_index], font=font, fill=img.getpixel((x, y))) # 用(x,y)处像素点的色值绘制字体
26+
img_ans.paste(img_child, (x * img_child_size, y * img_child_size))
27+
char_index = (char_index + 1) % len(text)
28+
29+
img_ans.save('moon-text.png')

doudou/2021-09-08-text-img/moon.png

201 KB
Loading

doudou/README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ Python技术 公众号文章代码库
88

99
## 实例代码
1010

11+
[吊炸天!十行代码我把情书藏进了小姐姐的微信头像里](https://github.com/JustDoPython/python-examples/tree/master/doudou/2021-09-08-text-img)
12+
1113
[解放双手,提高生产力,看我如何用 Python 实现自动化剪视频](https://github.com/JustDoPython/python-examples/tree/master/doudou/2021-06-30-pyautogui)
1214

1315
[谁说程序员不懂浪漫,当代码遇到文学...](https://github.com/JustDoPython/python-examples/tree/master/doudou/2021-03-09-programmer-romance)

0 commit comments

Comments
 (0)