情人节来了,教你个用 Python 表白的技巧( 七 )

首先 , 使用 pillow.Image读取图像 , 并使用load函数获取到每一个像素值 。

img_raw = Image.open(img_path) img_array = img_raw.load()

然后新建一张画布 , 并选好你要使用的字体和字体大小 。

img_new = Image.new( \"RGB\" img_raw.size ( 0 0 0 )) draw = ImageDraw.Draw(img_new) font = ImageFont. true type( 'C:/Windows/fonts/Dengl.ttf' font_size)

由于需要不断循环 “我喜欢你!” , 这五个字符 。 所以这里可以while循环 yield 来实现一个生成器 。

def character_generator (text) : while True : for i in range(len(text)): yield text[i

最后 , 要给这些字加上相应的颜色 , 写入新创建的画布中 。

for y in range ( 0 img_raw.size[ 1
font_size ): for x in range ( 0 img_raw.size[ 0
font_size ): draw. text ( (x y ) next ( ch_gen ) font_array[x y

推荐阅读