馬上圣誕節,快到了!
~
又到了一年一度表白的時候了
今天教你一個程式員方式的表白!
看一下效果圖:
要什么樣的,圖案都可以自定義的


首先,準備階段
收集你喜歡人(或者你)的照片,多多益善!
然后需要用到的環境
- python 3.6
- pycharm
- pygame
- PIL
- random
- os
接下來,寫代碼
分為兩部分
1.字體形狀
import pygame # 游戲模塊,字體功能, 第三方模塊 pip install pygame
text = '祝你成功!'
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)
# 根據什么邏輯貼圖 像素點
print(font_text.get_at((1, 1))[0])
# 根據像素點做分類: 劃分為一個二維串列
image_row_list = []
for x in range(height):
image_col_list = [] #
for y in range(width):
if font_text.get_at((y, x))[0] != 255: # 如果像素點不是白色
image_col_list.append(1) # 黑色添加資料1
else:
image_col_list.append(0) # 白色添加資料0
image_row_list.append(image_col_list)
for row in image_row_list:
print(row)
2.按照字體形狀去貼你準備好的圖片
from PIL import Image # 影像處理模塊, pip install pillow
import os # 目錄操作, 內置
import random # 亂數模塊, 隨機取一張圖片
# 貼圖 照片墻
width_len = len(image_row_list[0]) # 串列的寬
height_len = len(image_row_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_row_list[row][clo] == 1: # 如過串列的值為1, 就貼圖
# 讀取圖片
source_image = Image.open('images\\' + random.choice(os.listdir(r'images')))
# 修改圖片的大小
source_image = source_image.resize((img_size, img_size), Image.ANTIALIAS)
# 將圖片復制到new_image
new_image.paste(source_image, (clo * img_size, row * img_size))
# 照片強保存
print('正在生成照片墻...')
new_image.save(text + '.png')
print('保存完畢, 請在當前檔案專案下查找')
效果圖:

這樣就大功告成了!
學‘廢’了嘛?
歡迎留言評論!
文章沒看懂沒關系,我這還有視頻教程:表白墻←點擊左邊藍色文字就可以跳轉觀看了
Python基礎入門教程推薦:←點擊左邊藍色文字就可以跳轉觀看了
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/385419.html
標籤:其他
