把图片用字符拼起来
from PIL import Image, ImageDraw, ImageFont
class DrawPhotoWithMessage:
def __init__(self, img_path, save_path, font_size=5, message="我喜欢你!", font='myfont.ttf'):
self.font_size = font_size
self.text = message
self.img_path = img_path
self.font = font
self.save_path = save_path
@staticmethod
def each_char(text):
while True:
for i in range(len(text)):
yield text[i]
def draw_it(self):
img_raw = Image.open(self.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(self.font, self.font_size)
ch_gen = self.each_char(self.text)
for y in range(0, img_raw.size[1], self.font_size):
for x in range(0, img_raw.size[0], self.font_size):
draw.text((x, y), next(ch_gen), font=font, fill=img_array[x, y], direction=None)
img_new.convert('RGB').save(self.save_path)
if __name__ == '__main__':
draw_photo = DrawPhotoWithMessage("timg.jpg", "result.png")
draw_photo.draw_it()
你要是觉得写的还不错,就点个关注,可以评论区留下足迹,以后方便查看.
你要是觉得写的很辣鸡,评论区欢迎来对线!
欢迎转载!