Python入门实现七夕表白神器

 1 from PIL import Image, ImageDraw, ImageFont
 2 
 3 font_size = 7 #This var can change the Word's blank size.
 4 text = "我的小猪!" #filled with those word
 5 img_path = "F://SD.jpg"#image path
 6 
 7 img_raw = Image.open(img_path)#open the image
 8 img_array = img_raw.load()
 9 
10 img_new = Image.new("RGB", img_raw.size, (0, 0, 0))
11 draw = ImageDraw.Draw(img_new)
12 font = ImageFont.truetype('C:/Windows/fonts/Dengl.ttf', font_size)#Create a empty image
13 
14 def character_generator(text):#filled the font
15     while True:
16         for i in range(len(text)):
17             yield text[i]
18 
19 ch_gen = character_generator(text)
20 
21 for y in range(0, img_raw.size[1], font_size):
22     for x in range(0, img_raw.size[0], font_size):
23         draw.text((x, y), next(ch_gen), font=font, fill=img_array[x, y], direction=None)
24 
25 img_new.convert('RGB').save("F://SunJJ.jpg")

效果展示:

可以直接使用, 文中的参数可以修改如路径和字体大小等,由于图片的大小不同需要测试不同的font_size才能对齐。

 

posted @ 2020-02-14 15:57  DengSchoo  阅读(355)  评论(0编辑  收藏  举报