# -*- coding: utf-8 -*-
"""
Created on Sat Feb 15 13:54:10 2020
@author: panansi
"""
from PIL import Image, ImageDraw, ImageFont
font_size = 12
text = "你最漂亮 "
img_path = "F://006.jpg"
#首先使用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.truetype('C:/Windows/fonts/Dengl.ttf', font_size)
#由于需要不断地循环text中的字符,所以可以使用while循环yield来实现一个生成器
def character_generator(text):
while True:
for i in range(len(text)):
yield text[i]
ch_gen = character_generator(text)
#最后要给这些字加上相应的颜色,并写入新创建的画布中
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 = font, fill = img_array[x, y], direction=None)
#最后将成本保存
img_new.convert('RGB').save("F://save_06_12.jpeg")
拼成后的结果: