“两袖清风 怎敢误佳人?”来自程序员的浪漫,用Python把“喜欢你”写满你的照片(文字成像)

一年又过了,那个你错过的“TA”还记得吗?还会偶尔半夜一个人辗转吗?

错过的就让它错过吧,实在放不下的话就换一种方式聊以慰藉吧!!!

把想说的话,都藏在照片里吧~Python帮你实现,文字成像直接安排。


什么是 文字成像

将原图片经过 python 处理后,生成完全由纯文字组成的图像。

一、特效预览


处理前

处理后

 

细节放大后

 

二、程序原理

  • 输入你想隐藏的文字
  • 然后写到另一张跟照片同等大小的空白纸张上
  • 将相同位置的文字的颜色用照片上相同位置的颜色填充即可
  • 然后生成新的图片

 


三、程序源码

#!/usr/bin/env python
# encoding: utf-8

from PIL import Image, ImageDraw, ImageFont

class wordPicture:
    '''
     This is a main Class, the file contains all documents.
     One document contains paragraphs that have several sentences
     It loads the original file and converts the original file to new content
     Then the new content will be saved by this class
    '''
    def __init__(self):
        self.font_size = 7
        self.picture = 'assets/picture.jpeg'

    def hello(self):
        '''
        This is a welcome speech
        :return: self
        '''
        print('*' * 50)
        print(' ' * 20 + '文字成像')
        print(' ' * 5 + 'Author: autofelix  Date: 2022-01-18 13:14')
        print('*' * 50)
        return self

    def run(self):
        '''
        The program entry
        '''
        word = input('请输入你想说的:') or '我钟意你'

        resource = Image.open(self.picture)
        img_array = resource.load()

        image_new = Image.new('RGB', resource.size, (0, 0, 0))
        draw = ImageDraw.Draw(image_new)
        font = ImageFont.truetype('/System/Library/Fonts/PingFang.ttc', self.font_size)

        yield_word = self.character_generator(word)

        for y in range(0, resource.size[1], self.font_size):
            for x in range(0, resource.size[0], self.font_size):
                draw.text((x, y), next(yield_word), font=font, fill=img_array[x, y], direction=None)

        image_new.convert('RGB').save('result.jpeg')

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


if __name__ == '__main__':
    wordPicture().hello().run()


 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值