欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python表白,用Love组成一朵玫瑰花

程序员文章站 2022-07-14 16:15:07
...

上代码:

from PIL import Image,ImageDraw,ImageFont


font_size =20
#text ="Love You!"
text ="Love"
#img_path = "./demo.jpg"
img_path = "./flower.jpg"

img_raw=Image.open(img_path)
img_array =img_raw.load()	#get image as array

img_new =Image.new("RGB",img_raw.size,(0,0,0))
draw =ImageDraw.Draw(img_new)
font =ImageFont.truetype(font='C:/Windows/Fonts/AdobeArabic-Regular.otf',size=font_size) #win10 have the font lib
#font =ImageFont.truetype(font='C:/Windows/Fonts/Raleway Thin.ttf',size=font_size)

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("./flowerNew.jpg")

思路就是读取一张大图为array,新建一个蒙版,填入array中的值,同时在上面打印字符‘Love’,把字符输到很小的一块像素区域中,循环打印完整张图片,再保存即可。
不过有个问题是我打印不出中文,也许是字体库和编码的问题,尚未解决,我只打了英文。
python表白,用Love组成一朵玫瑰花

相关标签: python3