Some P words written in the front:
As long as you want to express yourself, you can express it every day! Don't say that there is no object, the object is obtained by yourself~
So how to fight for it? This tutorial tells you to technically synthesize a romantic photo wall~
Let's do it!
Step 1: Import the required modules
import os
import random
import pygame # pip install pygame
from PIL import Image # pip install pillow
小熊猫的python第二世界Q裙:660193417
Step 2: Initialize the module first
pygame.init()
Step 3: Define the font and set the initial size
text = '七夕快乐' # 字体形状, 可以修改成名字
size = 30 # 字体大小
# 定义字体,参数依次是字体、字体大小
font = pygame.font.Font('msyh.ttc', size)
print(font)
Step 4: Render the font
# 渲染字体,参数依次是被渲染的文字、是否无锯齿、字体颜色、背景颜色
# (0, 0, 0) 黑色 (255, 255, 255) 白色
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() # 宽度
Step 5: Pixel values, specified as a two-dimensional list
# 最后所有像素点会成为一个二维列表(形如[[1,2,3],[4,5,6]]),image_row_list是最外层的、总的列表
image_row_list = []
for x in range(height):
# image_col_list 是 image_row_list 中的每一个列表元素
image_col_list = []
for y in range(width):
# get_at((x,y))是返回像素点的像素值,[0]为第一个值R,
# 由于渲染后的图只有黑色和白色,所以只要[0]!=255,就是黑色
if font_text.get_at((y, x))[0] != 255: # 如果像素点不是 白色
image_col_list.append(1)
else:
image_col_list.append(0)
image_row_list.append(image_col_list)
for row in image_row_list:
print(row)
Step 6: Map according to the matrix
# 获取 image_row_list 列表的宽度和高度
width = len(image_row_list[0])
height = len(image_row_list)
# 设置最终输出的图片new_image,颜色模式RGB,宽和高分别放大100和100倍,背景色为白色。
new_image = Image.new('RGB', (100 * width, 100 * height), (255, 255, 255))
# 设置每一个(原图集)小图的裁剪尺寸
size = 100
# 遍历所有的像素点,如果像素点为1,也就是有颜色,则随机选择一张图片,将像素点填充为这张图片
for row in range(height):
for col in range(width):
if image_row_list[row][col] == 1:
# 从本地读取文件
source_image = Image.open('images\\' + random.choice(os.listdir(r'images')))
# 重新修改文件大小
source_image = source_image.resize((size, size), Image.ANTIALIAS) # 是否使用抗锯齿(antialias)功能
# 将图片复制到 new_image
new_image.paste(source_image, (col * size, row * size))
final output image
print('正在生成照片墙...')
new_image.save(text + '.jpg')
print('生成完毕, 请在当前文件项目下找照片墙文件')