家里的医生大大,让我把zen导出的图片一张张的排版到ppt或者Adobe Illustrator上。几百张图片。。。卑微的打工人。。。写段脚本吧。
import os
import re
from fpdf import FPDF
import cv2
def get_file(srcpath, patstr):
fpat = r'(' + patstr + r')' + r'_\S+'
pattern = re.compile(fpat)
ids = []
for file in os.listdir(srcpath):
presult = pattern.search(file)
if presult and os.path.isfile(os.path.join(srcpath, file)):
id = presult.group(1)
if id not in ids:
ids.append(id)
return ids
def format_image_age(srcpath, ids, flags=None):
if flags is None:
flags = ['c1+2+3+4', 'c1+2+3', 'c1+2', 'c1', 'c2', 'c3', 'c4']
image_paths = []
total_width = 0
total_height = 0
for id in ids:
temp_paths = []
total_width_tmp = 0
for flag in flags:
filename = os.path.join(srcpath, f'{id}_{flag}.jpg')
if os.path.exists(filename):
img = cv2.imread(filename)
temp_paths.append(filename)
total_width_tmp += img.shape[1]
total_height = max(total_height, img.shape[0])
if total_width_tmp > total_width:
total_width = total_width_tmp
image_paths.append(temp_paths)
total_width = total_width * 1.2
total_height = total_height * 1.2 * len(ids)
pdf = FPDF(format=(total_width, total_height))
pdf.add_page()
pdf.set_auto_page_break(auto=False, margin=15)
image_width, image_height, _ = img.shape
margin = 10
for i in range(len(image_paths)):
for j in range(len(image_paths[i])):
x = j * (image_width + margin) + margin
y = i * (image_height + margin) + margin
pdf.image(image_paths[i][j], x, y, image_width, image_height)
name = "_".join(ids)
pdf_file_name = os.path.join(srcpath, f'{name}.pdf')
pdf.output(pdf_file_name)
print(f'PDF save as {pdf_file_name}')
if __name__ == "__main__":
rootdir = r'D:\IF'
for root, dirs, files in os.walk(rootdir):
ids = get_file(root, r'\S+')
print(root, ids)
for i in range(0, len(ids), 2):
oneids = [ids[i]]
if i + 1 < len(ids):
oneids.append(ids[i + 1])
try:
format_image_age(root, oneids)
except Exception as e:
print(e)
使用的时候修,改一下红线圈出的整两句的参数就行。
workdir = r'F:\2024.1.22'中F:\2024.1.22是原图片的文件夹。get_file(workdir, r'Snap-\d+'),中r'Snap-\d+'图片名的正则(需要懂一点正则才行)。Snap-表示字符"Snap-", \d+表示多个数字字符。r'Snap-\d+'表示全部符合Snap-数字的图片。可以将文件夹和正则表达换成需要的。
结果在原文件夹下生成pdf文件