generated from john/python-template
56 lines
1.9 KiB
Python
56 lines
1.9 KiB
Python
import os
|
|
import fitz # PyMuPDF
|
|
|
|
# Configuration
|
|
PDF_PATH = "C:/Proton Drive/bbchops/My files/Archive/HigServiceRecords.pdf"
|
|
OUTPUT_DIR = "C:/Proton Drive/bbchops/My files/Archive/HigServiceRecords"
|
|
|
|
|
|
def extract_and_convert_images(pdf_path, output_dir):
|
|
# Ensure the output directory exists
|
|
if not os.path.exists(output_dir):
|
|
os.makedirs(output_dir)
|
|
|
|
# Open the PDF file
|
|
doc = fitz.open(pdf_path)
|
|
image_count = 0
|
|
|
|
print("Extracting and converting images to standard PNG...")
|
|
|
|
# Iterate through every page in the document
|
|
for page_num in range(len(doc)):
|
|
page = doc[page_num]
|
|
image_list = page.get_images(full=True)
|
|
|
|
# Loop through all images found on the current page
|
|
for img_index, img in enumerate(image_list):
|
|
xref = img[0]
|
|
|
|
try:
|
|
# Use PyMuPDF's Pixmap to handle the image data natively.
|
|
# This automatically decodes the JPX compression into standard pixels.
|
|
pix = fitz.Pixmap(doc, xref)
|
|
|
|
# If the image is in a weird color space (like CMYK), convert it to standard RGB
|
|
if pix.n - pix.alpha > 3:
|
|
pix = fitz.Pixmap(fitz.csRGB, pix)
|
|
|
|
image_count += 1
|
|
filename = f"record_page_{page_num + 1:03d}_img_{img_index + 1}.png"
|
|
filepath = os.path.join(output_dir, filename)
|
|
|
|
# Save directly as a clean, uncompressed PNG file
|
|
pix.save(filepath)
|
|
print(f"Converted and saved: {filename}")
|
|
|
|
# Free up memory
|
|
pix = None
|
|
|
|
except Exception as e:
|
|
print(f"Could not convert image on page {page_num + 1}: {e}")
|
|
|
|
print(f"\nSuccess! Converted and saved {image_count} standard PNG images to '{output_dir}'.")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
extract_and_convert_images(PDF_PATH, OUTPUT_DIR) |