如何使用 Python 从 PDF 中提取图像,同时保留其原始分辨率?

DDD
发布: 2024-10-22 07:52:30
原创
583 人浏览过

How Can You Extract Images from PDFs Using Python While Preserving Their Original Resolution?

使用 Python 从 PDF 中提取图像而无需重新采样

高效地从 PDF 文档中提取所有图像,同时保留其原始分辨率和格式而无需重新采样,您可以使用 PyMuPDF 模块。该模块为图像提取提供了有效的解决方案,将图像输出为PNG文件。

使用PyMuPDF:

<code class="python">import fitz

# Open the PDF document
doc = fitz.open("file.pdf")

# Iterate through the pages
for i in range(len(doc)):
    # Extract images from the current page
    for img in doc.getPageImageList(i):
        # Retrieve the image's XREF and create a Pixmap
        xref = img[0]
        pix = fitz.Pixmap(doc, xref)

        # Check if the image is grayscale or RGB
        if pix.n < 5:
            # Save the image in PNG format
            pix.writePNG("p%s-%s.png" % (i, xref))

        # If the image is CMYK, convert it to RGB and save
        else:
            pix1 = fitz.Pixmap(fitz.csRGB, pix)
            pix1.writePNG("p%s-%s.png" % (i, xref))
            pix1 = None

        # Release the Pixmaps
        pix = None</code>
登录后复制

增强功能:

支持 fitz 1.19.6 的脚本更新版本:

<code class="python">import os
import fitz
from tqdm import tqdm

# Specify the work directory
workdir = "your_folder"

# Iterate through the PDFs in the directory
for each_path in os.listdir(workdir):
    if ".pdf" in each_path:
        # Open the PDF document
        doc = fitz.Document(os.path.join(workdir, each_path))

        for i in tqdm(range(len(doc)), desc="pages"):
            for img in tqdm(doc.get_page_images(i), desc="page_images"):
                # Extract the image and save as PNG
                xref = img[0]
                image = doc.extract_image(xref)
                pix = fitz.Pixmap(doc, xref)
                pix.save(os.path.join(workdir, "%s_p%s-%s.png" % (each_path[:-4], i, xref)))</code>
登录后复制

此增强的脚本提供进度条以增加可见性,并使用一致的文件命名约定保存提取的图像。

以上是如何使用 Python 从 PDF 中提取图像,同时保留其原始分辨率?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!