[Asm] 纯文本查看 复制代码 # 合并图片
import os,sys
from PIL import Image as imim
from tkinter import *
import tkinter.filedialog
import tkinter as tk
from tkinter import filedialog
def merge_images(image_folder, jpg,mer_num):
# 获取所有图像文件的列表
sorted_files = [os.path.join(image_folder, f) for f in os.listdir(image_folder) if f.endswith('.'+jpg)]
image_count = len(sorted_files)
if image_count == 0:
print('No image files found in the directory:', image_folder)
return
# 根据文件名进行排序
# sorted_files = sorted(image_files)
# 注意(x.split('_')[1])[:-4]) 为切割字符串为数字
sorted_files.sort(key = lambda x:int(x.split('\\')[-1][:-4]))
# 计算新图片的宽度和高度
new_width = new_height = mer_height = 0
new_img=None
for i,image in enumerate(sorted_files):
image = imim.open(image)
print(sorted_files[i])
if(i%mer_num==0 or i==image_count-1):
new_width = new_height = mer_height = 0
if(new_img!=None):
path = image_folder+'/合成/'
if not os.path.exists(path):
os.mkdir(path)
if(i==image_count-1):
new_img.save(path+str(i//mer_num+1)+'.jpg')
print('保存图片:'+str(i//mer_num+1)+'.jpg')
else:
new_img.save(path+str(i//mer_num)+'.jpg')
print('保存图片:'+str(i//mer_num)+'.jpg')
for num in range(min(mer_num,image_count,image_count-i)):
# 加载图片
img1 = imim.open(sorted_files[i//mer_num*mer_num+num])
new_height = new_height+img1.height
new_width = max(img1.width, new_width)
new_img = imim.new('RGB', (new_width, new_height))
# 拼接两张图片
new_img.paste(image, (0,mer_height))
mer_height=mer_height+image.height
else:
# 拼接两张图片
new_img.paste(image, (0,mer_height))
mer_height=mer_height+image.height
def askfile(initialdir=r"C:\Users\Administrator\Desktop"):
return tkinter.filedialog.askdirectory(
title="选择一个文件夹..",
initialdir=initialdir,
parent=root
)
mainargv=sys.argv
root = tk.Tk()
root.withdraw() # 隐藏主窗口
root.attributes('-topmost', 1)# 让文件选择器窗口始终在顶层
if len(mainargv) > 1: # 这里是 希望用户把图片文件拖拽到程序图标上
image_folder=mainargv[1]
else: # 没有拖拽 就打开文件选择器
image_folder=askfile(os.getcwd())
# 用法示例
jpg = 'jpg' #图片格式
mer_num = 40 #图片合并数量
merge_images(image_folder,jpg,mer_num)
是否在纠结刚爬好的漫画图片是一张一张的,上面的代码可以将文件夹下的漫画图片合成一张,有在APP上观看的效果
|