停止对 PDF 截图:开发者提取高分辨率图像指南

发布: (2025年12月14日 GMT+8 00:40)
2 min read
原文: Dev.to

Source: Dev.to

糟糕的做法

打开 PDF,放大后截屏。
结果:像素化、低质量的 PNG,且背景颜色不对。

正确的做法:直接从 PDF 中提取图像

使用 Python(PyMuPDF)

安装库

pip install pymupdf

提取脚本

import fitz  # PyMuPDF

def get_images(pdf_file):
    doc = fitz.open(pdf_file)
    print(f"Processing: {pdf_file}")

    for page_index in range(len(doc)):
        page = doc[page_index]
        image_list = page.get_images()

        for img_index, img in enumerate(image_list):
            xref = img[0]
            base_image = doc.extract_image(xref)
            image_bytes = base_image["image"]
            ext = base_image["ext"]

            # Save the image
            filename = f"page{page_index+1}_img{img_index}.{ext}"
            with open(filename, "wb") as f:
                f.write(image_bytes)
            print(f"Saved: {filename}")

get_images("design_mockup.pdf")

该脚本直接提取 PDF 中嵌入的原始文件,保留原始质量(透明 PNG、高分辨率 JPEG 等)。

浏览器方式(无需代码)

一个免费的在线工具 PDFConvertLabs 在安全的后端执行相同的提取,并提供拖拽界面。它还能自动完成 CMYK 到 RGB 的转换。

在线从 PDF 中提取图像 (请替换为实际 URL)

Back to Blog

相关文章

阅读更多 »

使用 Python 自动生成法律文件

为什么要自动化法律文件?处理法律文件——例如离婚表格、协议或信件——可能是重复且耗时的。Python 让这变得容易……