import fitz
import re
import os
import time
# 使用正则表达式查找PDF中的图片
def find_img(path, img_path): #PDF的路径和图片保存的路径
t0 = time.time() # 生成图片初始时间
checkXO = r"/Type(?= */XObject)" # 使用正则表达式来查找图片
checkIM = r"/Subtype(?= */Image)"
doc = fitz.open(path) # 打开pdf文件
imgcount = 0 # 图片计数
lenXREF = doc.xref_length() # 获取对象数量长度
# 打印PDF的信息
print("文件名:{}, 页数: {}, 对象: {}".format(path, len(doc), lenXREF - 1))
# 遍历每一个对象
for i in range(1, lenXREF):
text = doc.xref_object(i) # 定义对象字符串
isXObject = re.search(checkXO, text) # 使用正则表达式查看是否是对象
isImage = re.search(checkIM, text) # 使用正则表达式查看是否是图片
if not isXObject or not isImage: # 如果不是对象也不是图片,则continue
continue
imgcount += 1
pix = fitz.Pixmap(doc, i) # 生成图像对象
new_name = "图片{}.png".format(imgcount) # 生成图片的名称
if pix.n < 5: # 如果pix.n<5,可以直接存为PNG
pix.save(os.path.join(img_path, new_name))
else: # 否则先转换CMYK
pix0 = fitz.Pixmap(fitz.csRGB, pix)
pix0.save(os.path.join(img_path, new_name))
pix0 = None
pix = None # 释放资源
t1 = time.time() # 图片完成时间
print("运行时间:{}s".format(t1 - t0))
if __name__ == '__main__':
pdfpath = r'./练习文件/展览会清单 (2).pdf'
imgpath = r'图片'
if os.path.exists(imgpath):
print("文件夹已存在,请重新创建新文件夹!")
raise SystemExit
else:
os.mkdir(imgpath)
m = find_img(pdfpath, imgpath)
用Python从PDF文件中提取图片
最新推荐文章于 2025-04-13 23:02:41 发布