[Teacher’s Day Special] Make a happy Teacher’s Day photo wall

Reason for writing:

        Teachers' Day is here, and there are more or less many teachers around me. Basically, I don't remember the teachers I knew before. I will always know some Japanese teachers in the future. Programmers should celebrate Teachers' Day in their own way. After thinking about it, I decided to make a photo wall.

Project link  airhandsome/wall-of-text: Use picture to compose text (github.com)

write the code:

       This kind of code must be processed with the all-purpose python. Although I have basically forgotten all the CV I used before, the advantage of python is that we can find some useful libraries anytime and anywhere. Since it is a photo wall, it must be divided into three aspects:

1. Take photos

Here, we use a legal tool that everyone is familiar with to request some public pictures. It should not be considered a violation.

Here I selected a Happy Teachers' Day post from Baidu Tieba. There are more than 20 pictures in it, which is quite festive. At this time, I only need to parse the BDE_Image tag to use it.

def getJPGs(url):
    # 获取url链接的内容
    html = requests.get(url)
    soup = BeautifulSoup(html, "html.parser")
    # 查找 class 为 BDE_Image 的图片标签
    image_tags = soup.find_all("img", class_="BDE_Image")
    # 提取图片链接
    image_urls = [img["src"] for img in image_tags]
    return image_urls


#保存单张图片
def downloadJPG(imgUrl, fileName):
    response = requests.get(imgUrl)
    with open(fileName, 'wb') as f:
        f.write(response.content)

#保存图片列表
def batchDownloadJPGs(imgUrls, path='pixels/'):
    if not os.path.exists(path):
        os.mkdir(path)

    count = 0
    for url in imgUrls:
        downloadJPG(url, ''.join([path, '{0}.jpg'.format(count)]))
        print('number: ' + str(count))
        count = count + 1

if __name__ == "__main__":
    url = 'https://tieba.baidu.com/p/8594160102'
    jpgs = getJPGs(url)
    batchDownloadJPGs(jpgs)

2. Get the base material

What is the base material? What shape should this photo wall be formed into? For example, if I just want to form text, then I can form it. I need to use the entire Python library.

def get_text_position(text):
    pygame.init()
    font_size = 30  # 字体大小pygame.init()  # 模块的初始化  为什么  pygame不是我开发的, 我们用的别人  python语法  三原色
    font = pygame.font.Font('msyh.ttc', font_size)
    print(font)  # 字体的渲染
    # True 锯齿化   rgb 颜色 由三原色组成  黑  白
    font_text = font.render(text, True, (0, 0, 0), (255, 255, 255))
    print(font_text)  # 获取字体的宽高
    height = font_text.get_height()  # 高度
    width = font_text.get_width()  # 宽度
    print('height: ', height)
    print('width: ', width)  # 根据什么逻辑贴图  像素点
    image_row_list = []
    #缩放程度,1就是原图大小,2就是缩小为原来的一半
    shrink_part = 1
    for x in range(height // shrink_part):
        image_col_list = []
        for y in range(width // shrink_part):
            val = 0
            for i in range(shrink_part):
                for j in range(shrink_part):
                    x_index = x * shrink_part + i
                    y_index = y * shrink_part + j
                    val += font_text.get_at((y_index, x_index))[0]
            val //= shrink_part * shrink_part
            if val != 255:  # 如果像素点不是白色
                image_col_list.append(1)  # 黑色添加数据1
            else:
                image_col_list.append(0)  # 白色添加数据0
        image_row_list.append(image_col_list)

    return list(image_row_list)

The text here is to fill in the content you want. For example, if I want to generate "Happy Teachers' Day", the parameter is "Happy Teachers' Day"

3. Draw a picture

Just pass the result of the second step in directly and you can draw it. In fact, if the matrix in the second step is 1, randomly put a picture on it. Save it for last.

def drawImage(image_list):
    width_len = len(image_list[0])  # 列表的宽
    height_len = len(image_list)  # # 列表的高# 创建图片
    new_image = Image.new('RGB', (width_len * 100, height_len * 100), (255, 255, 255))  # 贴图
    img_size = 100  # 初始图片尺寸
    for row in range(height_len):
        for clo in range(width_len):
            if image_list[row][clo] == 1:  # 如过列表的值为1, 就贴图# 读取图片
                source_image = Image.open('pixels/' + random.choice(os.listdir(r'pixels')))# 修改图片的大小
                source_image = source_image.resize((img_size, img_size), Image.LANCZOS)# 将图片复制到new_image
                new_image.paste(source_image, (clo * img_size, row * img_size))# 照片强保存
    print('正在生成照片墙...')
    new_image.save('output.png')
    print('保存完毕, 请在当前文件项目下查找')

Effect

The picture without scaling is about 14M.

wall-of-text/output_1.png at main · airhandsome/wall-of-text (github.com)icon-default.png?t=N7T8https://github.com/airhandsome/wall-of-text/blob/main/output_1.png

The picture with shrink_part = 2 is about 6M. In fact, every 2*2 pixels are merged into 1 pixel, so it will look rough. However, since it will be compressed when sent by WeChat, it will have no effect, so it may be better to be rougher. point.

wall-of-text/output.png at main · airhandsome/wall-of-text (github.com)icon-default.png?t=N7T8https://github.com/airhandsome/wall-of-text/blob/main/output.png

Guess you like

Origin blog.csdn.net/u013379032/article/details/132797646