本篇文章在提供一個圖片產生器 用簡單小程式自動將不同圖層圖片做合成 進行不同排列組合 然後生成新的圖片
希望對於有意生產NFT圖片的朋友 有所幫助
需要進階客製化版本的朋友 可連絡 service@elitekeyboarder.com
設計概念
主要概念是 : 我們去讀取不同圖層的圖片 然後生成新的圖片
首先 我們設計好不同的圖片檔案 做不同的設計
把檔案置放於 “Face”, “Eye”, “Mouth”, “Head” 目錄中
記住 務必把圖層背景設定為 “透明” 才能在疊加圖層的時候產生效果
實際的程式循環控制 我們是使用多層式的巢狀迴圈 以確定每一個圖層檔案都能被使用到
並且所有的排列組合情況 都能確實地生成
整個程式邏輯非常簡單
假設我們有2個臉部設計, 2個眼部設計, 2個口部設計, 2個頭部設計
最終結果 我們就會產生 2x2x2x2 = 16 成品檔案
Python 原始碼
import os;
from os import listdir
from os.path import isfile, isdir, join
import shutil;
from PIL import Image
# 新圖片檔案之計數器
cnt = 0;
# NFT 根源目錄
# 內部會包含 "Face", "Eye", "Mouth", "Head" 目錄
nft_home_dir = "C:/AAA/BBB/CCC";
files=[]
# 原始圖檔是設計成多個不同的元件
# 圖片目錄包含 "Face", "Eye", "Mouth", "Head"
# 要生成的目標圖檔會依據原始圖檔做不同圖層的合成
check_dir_face = nft_home_dir + "/Face"
files_face = listdir(check_dir_face);
check_dir_eye = nft_home_dir + "/Eye"
files_eye = listdir(check_dir_eye);
check_dir_mouth = nft_home_dir + "/Mouth"
files_mouth = listdir(check_dir_mouth);
check_dir_head = nft_home_dir + "/Head"
files_head = listdir(check_dir_head);
# 生成的目標圖檔之目錄
output_dir = "result";
if os.path.exists(output_dir) :
shutil.rmtree(output_dir);
os.makedirs(output_dir);
# Log 檔案
file_log = open("./generation_history.log", 'w');
# 此處採用多層式迴圈去使用各圖層作排列組合
for f_face in files_face:
name_face = os.path.splitext(f_face)[0];
fullpath = join(check_dir_face, f_face);
if isfile(fullpath):
for f_eye in files_eye:
name_eye = os.path.splitext(f_eye)[0];
fullpath = join(check_dir_eye, f_eye);
if isfile(fullpath):
for f_mouth in files_mouth:
name_mouth = os.path.splitext(f_mouth)[0];
fullpath = join(check_dir_mouth, f_mouth);
if isfile(fullpath):
for f_head in files_head:
name_head = os.path.splitext(f_head)[0];
fullpath = join(check_dir_head, f_head);
if isfile(fullpath):
# 目標檔案的名字
target_filename = name_face + "_" + name_eye + "_" + name_mouth + "_" + name_head + ".png";
layer_face = Image.open(check_dir_face + "/" + f_face).convert('RGBA');
layer_eye = Image.open(check_dir_eye + "/" + f_eye).convert('RGBA');
layer_mouth = Image.open(check_dir_mouth + "/" + f_mouth).convert('RGBA');
layer_head = Image.open(check_dir_head + "/" + f_head).convert('RGBA');
# 從上層的圖 黏貼在其次的圖層
# 由上至下 逐一處理
layer_mouth.paste(layer_head, (0, 0), layer_head);
layer_eye.paste(layer_mouth, (0, 0), layer_mouth);
layer_face.paste(layer_eye, (0, 0), layer_eye);
# 寫出目標圖片檔案
layer_face.save(output_dir + "/" + target_filename, format="png");
# 寫出 log
file_log.write(output_dir + "/" + target_filename + "\n");
file_log.flush();
cnt = cnt + 1; # Counter increment
# 顯示螢幕訊息
print(str(cnt) ,"outputting file", target_filename);
# 顯示最後完成之圖片檔案計數器
print("Final count =", cnt);
好厲害,謝謝分享