之前论坛里找了几个,都会出现,如果图片是PNG的话,就错误提示“cannot save mode RGBA”,加了convert('RGB')也不行,试了好多方法,最终找到可以用的办法
学习PYTHON时间不长,代码有点乱
[Python] 纯文本查看 复制代码 from PIL import Image
from tkinter import filedialog
import os
def to_pdf(folder_path):
files = os.listdir(folder_path)
img_files = []
sources = []
for file in files:
if 'png' in file or 'jpg' in file:
img_files.append(folder_path + file)
img_files.sort()
if 'png' in img_files[0]:
output1 = Image.open(img_files[0])
output = Image.new('RGB',output1.size,(255,255,255))
output.paste(output1,mask=output1.split()[3])
img_files.pop(0)
elif 'jpg' in img_files[0]:
output = Image.open(img_files[0])
img_files.pop(0)
for file in img_files:
if 'png' in file:
rgba_file = Image.open(file)
rgb_file = Image.new('RGB',rgba_file.size,(255,255,255))
rgb_file.paste(rgba_file, mask=rgba_file.split()[3])
sources.append(rgb_file)
elif 'jpg' in file:
img_file = Image.open(file)
if img_file.mode == 'RGB':
img_file = img_file.convert('RGB')
sources.append(img_file)
pdf_file_path = filedialog.asksaveasfilename(title='请选择PDF文件保存目录',filetypes=[('PDF文件','.pdf')])
if pdf_file_path.endswith('.pdf') == False:
pdf_file_path = pdf_file_path + '.pdf'
output.save(pdf_file_path, "pdf", save_all=True, append_images=sources)
if __name__ == "__main__":
img_dir = filedialog.askdirectory(title='请选择图片所在文件夹') + '/'
to_pdf(img_dir) |