[Python] Extracting Images from a PDF using PyMuPDF gives broken output images

Discussão em 'Python' iniciado por Stack, Março 31, 2025.

  1. Stack

    Stack Membro Participativo

    The code i am using to extract the images is

    def extract_images_from_pdfs(pdf_list):
    import fitz # PyMuPDF

    output_dir = "C:/Users/""/"""/image"
    os.makedirs(output_dir, exist_ok=True)

    for pdf_path in pdf_list:
    pdf_name = os.path.splitext(os.path.basename(pdf_path))[0]


    # Open the PDF
    pdf_document = fitz.open(pdf_path)

    # Track the count of images extracted per page
    image_count = 0

    for page_num, page in enumerate(pdf_document):
    # Get the images on this page
    image_list = page.get_images(full=True)

    if not image_list:
    print(f"No images found on page {page_num+1} of {pdf_name}")
    continue

    # Process each image
    for img_index, img in enumerate(image_list):
    xref = img[0]
    base_image = pdf_document.extract_image(xref)

    if base_image:
    image_bytes = base_image["image"]
    image_ext = base_image["ext"]

    # Convert bytes to image
    image = Image.open(io.BytesIO(image_bytes))

    # Save the image
    image_name = f"{pdf_name}_image_{image_count}.{image_ext}"
    image_path = os.path.join(output_dir, image_name)

    image.save(image_path)

    image_count += 1

    pdf_document.close()
    print(f"Extracted {image_count} images from {pdf_name}")


    extract_images_from_pdfs(files_list)


    The input (files_list) is just a list containing all the names of my pdf's [​IMG]

    [​IMG]

    When i should get something like

    [​IMG]

    Could it be that the images on the PDF are encrypted / accessible and is there a work around for this.

    Any help is greatly appreciated.

    testingpdfexampaper.tiiny.site This is the URL for the PDF

    Continue reading...

Compartilhe esta Página