使用PIL将多张JPEG转PDF时a.jpg重复保存的问题求助
Hey there! Let's sort out that annoying duplicate a.jpg in your generated PDF. Here's what's going wrong and how to fix it:
What's Causing the Duplicate?
When you call img1.save() with save_all=True and pass append_images=[img1, img2], PIL does two things:
- It saves
img1as the first page of the PDF. - Then it appends every image in the
append_imageslist—so that'simg1again (second page) andimg2(third page).
That's why you end up with two copies of a.jpg instead of one!
The Fix
We just need to make sure we don't include img1 twice. Instead of passing the full images list to append_images, we'll only pass the images after the first one (so just img2).
Corrected Code
I also fixed a couple of small bugs in your original code (missing import, typo in resolution) to make it work properly:
import random from PIL import Image # Don't forget this import! def print_hi(name): folder = "C:/Users/arjay/Documents/IntellijBackgrounds/" img1 = Image.open(folder + "a.jpg") img2 = Image.open(folder + "b.jpg") # Generate random PDF filename random_pdf_name = folder for _ in range(5): # Add random uppercase letter random_pdf_name += chr(random.randint(65, 90)) # Add random number and file extension random_pdf_name += str(random.randint(1, 1000)) + ".pdf" images = [img1, img2] if len(images) > 1: # Save img1 as first page, append ONLY the remaining images img1.save( random_pdf_name, "pdf", resolution=100.0, save_all=True, append_images=images[1:] # This is the key fix! ) else: img1.save(random_pdf_name, "pdf", resolution=100.0, save_all=True) print("Successfully converted images to", random_pdf_name) if __name__ == '__main__': print_hi('PyCharm')
Key Changes Explained
append_images=images[1:]: This slices the list to only include images starting from index 1 (so justimg2), preventingimg1from being added twice.- Added
from PIL import Image: Your original code was missing this, which would have thrown aNameError. - Fixed the typo
reolution→resolution: That would have caused PIL to ignore your resolution setting. - Cleaned up the random filename generation to remove redundant variable assignments.
Alternative Way to Write It
If you want to make it even clearer that you're handling all images as a set, you can do this instead (same end result):
images = [img1, img2] # Use the first image as the base, append the rest images[0].save( random_pdf_name, format="PDF", resolution=100.0, save_all=True, append_images=images[1:] )
内容的提问来源于stack exchange,提问作者Arjay

