python实现图片暗藏表白效果

今天在刷微博的时候看到一组暗藏"我喜欢你"的图片
突然想了解是怎么样实现的
参考博客:https://blog.csdn.net/kangqiao0422/article/details/104310848?utm_source=app

原图

python实现图片暗藏表白效果_第1张图片

效果图

python实现图片暗藏表白效果_第2张图片

是不是看不清楚,我们放大来看看
python实现图片暗藏表白效果_第3张图片

代码实现

需要用到的是PIL库,安装(pip install Pillow)
PIL文档请戳下面链接
https://pillow.readthedocs.io/en/stable/handbook/tutorial.html#using-the-image-class

全部代码:

from PIL import Image, ImageDraw, ImageFont, ImageMode

#设置字体打印大小
font_size = 15
#设置添加的名字
text = "我喜欢你"
img_path = "2.jpg"

#导入指定的图片
img_raw = Image.open(img_path)        #注意图片的路径
#使用load函数获取到每一个像素值
img_array = img_raw.load()

# 新建画布并设置好相关参数
img_new = Image.new("RGB", img_raw.size, (255, 255, 255))     #参数: image = Image.new(mode,size,color)
#添加字体
draw = ImageDraw.Draw(img_new)
# 字体,可以使用windows系统自带的(可打开c盘的fonts文件夹查看你所喜欢的文字)
font = ImageFont.truetype('C:/Windows/fonts/Dengl.ttf', 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("我喜欢你.png")

你可能感兴趣的:(python实现图片暗藏表白效果)