自学内容网 自学内容网

Python应用—从pdf中保存图片

import fitz  # PyMuPDF


def extract_images_from_pdf(pdf_path, output_folder):
    # 打开PDF文件
    doc = fitz.open(pdf_path)

    # 遍历PDF的每一页
    for page_number in range(len(doc)):
        # 获取当前页
        page = doc[page_number]

        # 遍历页面中的所有图片
        for img_index, img in enumerate(page.get_images(full=True), start=1):
            xref = img[0]  # xref是图片的引用
            base_image = doc.extract_image(xref)  # 提取图片
            image_bytes = base_image["image"]  # 获取图片的字节数据

            # 保存图片
            image_name = f"image_page{page_number + 1}_{img_index}.png"
            image_path = output_folder + image_name
            with open(image_path, "wb") as image_file:
                image_file.write(image_bytes)

            print(f"Image saved: {image_path}")

    # 关闭文档
    doc.close()


# PDF文件路径
pdf_path = '1.pdf'
# 输出图片的文件夹路径
output_folder = 'output_images'

# 调用函数
extract_images_from_pdf(pdf_path, output_folder)

原文地址:https://blog.csdn.net/weixin_55144746/article/details/140491557

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!