使用 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中文网其他相关文章!