PDF文件中的图片提取
pdf中保存的图像文件有两种,1种直接是把原图片的数据复制进文档中,另外一种是经过压缩的图片,这种图片的提取并非只是简单的解压缩就能解决的。
1.直接保存图片格式的
例如上图中的例子,直接可以看到JFIF头,这种直接把 stream 和endstream中间的内容保存下来,去掉头尾的0xa 就可以看到图片了。
2.压缩图片
像这样的图片如果仅仅是解压缩:
解压缩之后会是像下边这样的数据,
这个数据保存之后是没办法看到图片的。
原因:http://itext.2136553.n4.nabble.com/Extract-FlateDecode-image-td2158485.html
A FlateDecoded image isn't in any standard image format - it's just a
"raw 2D array of colorant values".You will need to write the (complex) code to convert that array into
a standard image format - taking into consideration that images in
PDF can be in 9 different colorspaces, with varying bits per
components, etc.FlateDecoded图像不是任何标准图像格式-仅仅是
“原始2D着色剂值数组”。您将需要编写(复杂)代码以将该数组转换
为标准图像格式-考虑到
PDF中的图像 可以采用9种不同的色彩空间,每个
组件的位都不同 ,等等
好在是已经有人写了这样的代码:https://gist.github.com/gstorer/f6a9f1dfe41e8e64dcf58d07afa9ab2a
使用此代码需要安装PyPDF2
Usage:
PDF_extract_images file.pdf page1 page2 page3
代码此地保存一份:
# coding=utf-8from __future__ import print_function
"""
The MIT License (MIT)
Copyright (c) 2018 Louis Abraham <louis.abraham@yahoo.fr>
Copyright ©2016 Ronan Paixão
Copyright (c) 2018 Gerald Storer
\x1B[34m\033[F\033[F
Extract the images from a pdf
\x1B[0m\x1B[36m\033[F\033[F
Supports most formats, but has some bugs (even pdfimages has).
For example, with encoding /CCITTFaxDecode, the image is sometimes flipped.
If you have a bug, see
https://stackoverflow.com/questions/2693820/extract-images-from-pdf-without-resampling-in-python
for other solutions or drop me an email with your pdf file attached
\x1B[0m\x1B[35m\033[F\033[F
TODO:- add support for range queries
\x1B[0m\033[1m\033[F\033[F
Links:PDF format: http://www.adobe.com/content/dam/Adobe/en/devnet/acrobat/pdfs/pdf_reference_1-7.pdfCCITT Group 4: https://www.itu.int/rec/dologin_pub.asp?lang=e&id=T-REC-T.6-198811-I!!PDF-E&type=itemsExtract images from pdf: http://stackoverflow.com/questions/2693820/extract-images-from-pdf-without-resampling-in-pythonExtract images coded with CCITTFaxDecode in .net: http://stackoverflow.com/questions/2641770/extracting-image-from-pdf-with-ccittfaxdecode-filterTIFF format and tags: http://www.awaresystems.be/imaging/tiff/faq.html/Index support: https://github.com/ronanpaixao/PyPDFTK/blob/master/pdf_images.py
Usage:PDF_extract_images file.pdf page1 page2 page3 …
\033[0m\033[F\033[F
"""# https://stackoverflow.com/questions/2693820/extract-images-from-pdf-without-resampling-in-pythonimport PyPDF2from PIL import Image, ImageOpsimport sys
import struct
from os import path
import warnings
import io
from collections import namedtuple
warnings.filterwarnings("ignore")img_modes = {'/DeviceRGB': 'RGB', '/DefaultRGB': 'RGB','/DeviceCMYK': 'CMYK', '/DefaultCMYK': 'CMYK','/DeviceGray': 'L', '/DefaultGray': 'L','/Indexed': 'P'}PdfImage = namedtuple('PdfImage', ['data', 'format','image_name'])def tiff_header_for_CCITT(width, height, img_size, CCITT_group=4):# http://www.fileformat.info/format/tiff/corion.htmfields = 8tiff_header_struct = '<' + '2s' + 'H' + 'L' + 'H' + 'HHLL' * fields + 'L'return struct.pack(tiff_header_struct,b'II', # Byte order indication: Little indian42, # Version number (always 42)8, # Offset to first IFDfields, # Number of tags in IFD256, 4, 1, width, # ImageWidth, LONG, 1, width257, 4, 1, height, # ImageLength, LONG, 1, lenght258, 3, 1, 1, # BitsPerSample, SHORT, 1, 1259, 3, 1, CCITT_group, # Compression, SHORT, 1, 4 = CCITT Group 4 fax encoding262, 3, 1, 0, # Threshholding, SHORT, 1, 0 = WhiteIsZero# StripOffsets, LONG, 1, len of header273, 4, 1, struct.calcsize(tiff_header_struct),278, 4, 1, height, # RowsPerStrip, LONG, 1, length279, 4, 1, img_size, # StripByteCounts, LONG, 1, size of image0 # last IFD)def extract_images_from_pdf_page(xObject):image_list = []xObject = xObject['/Resources']['/XObject'].getObject()for obj in xObject:o = xObject[obj]if xObject[obj]['/Subtype'] == '/Image':size = (xObject[obj]['/Width'], xObject[obj]['/Height'])# getData() does not work for CCITTFaxDecode or DCTDecode# as of 1 Aug 2018. Not sure about JPXDecode.data = xObject[obj]._datacolor_space = xObject[obj]['/ColorSpace']if '/FlateDecode' in xObject[obj]['/Filter']:if isinstance(color_space, PyPDF2.generic.ArrayObject) and color_space[0] == '/Indexed':color_space, base, hival, lookup = [v.getObject() for v in color_space] # pg 262mode = img_modes[color_space]data = xObject[obj].getData() # need to use getData() hereimg = Image.frombytes(mode, size, data)if color_space == '/Indexed':img.putpalette(lookup.getData())img = img.convert('RGB')imgByteArr = io.BytesIO()img.save(imgByteArr,format='PNG')image_list.append(PdfImage(data=imgByteArr,format='PNG',image_name=obj[1:]))elif '/DCTDecode' in xObject[obj]['/Filter']:image_list.append(PdfImage(data=io.BytesIO(data),format='JPG',image_name=obj[1:]))elif '/JPXDecode' in xObject[obj]['/Filter']:image_list.append(PdfImage(data=io.BytesIO(data),format='JP2',image_name=obj[1:]))elif '/CCITTFaxDecode' in xObject[obj]['/Filter']:if xObject[obj]['/DecodeParms']['/K'] == -1:CCITT_group = 4else:CCITT_group = 3data = xObject[obj]._data img_size = len(data)tiff_header = tiff_header_for_CCITT(size[0], size[1], img_size, CCITT_group)im = Image.open(io.BytesIO(tiff_header + data))if xObject[obj].get('/BitsPerComponent') == 1:# experimental condition# http://users.fred.net/tds/leftdna/sciencetiff.htmlim = ImageOps.flip(im)imgByteArr = io.BytesIO()img.save(imgByteArr,format='PNG')image_list.append(PdfImage(data=imgByteArr,format='PNG',image_name=obj[1:]))else:print ('Unhandled image type: {}'.format(xObject[obj]['/Filter']))else:image_list += extract_images_from_pdf_page(xObject[obj])return image_listif __name__ == '__main__':try:filename = sys.argv[1]pages = sys.argv[2:]pages = list(map(int, pages))abspath = path.abspath(filename)except BaseException:print(__doc__, file=sys.stderr)sys.exit()file = PyPDF2.PdfFileReader(open(filename, "rb"))number = 0for p in pages:page0 = file.getPage(p - 1)image_list = extract_images_from_pdf_page(page0)number += len(image_list)for pdf_image in image_list:img = Image.open(pdf_image.data)image_path = "{} - p. {} - {}.{}".format(abspath[:-4], p, pdf_image.image_name,pdf_image.format)img.save(image_path)print('-' * 20)print('{} extracted images'.format(number))print('-' * 20)
PDF文件中的图片提取相关推荐
- 网页导出pdf不完整_怎样将PDF文件中的图片提取出来并保存?
日常工作或学习中经常会接触很多PDF文档,有时其中有些图片是我们需要用到的,应该如何将这些图片从PDF文件中提取出来并且保存呢? 我们可以用PDF编辑器来实现这个需求,首先用极速PDF编辑器打开我们需 ...
- Python脚本工具,PyMuPDF批量提取PDF文件中的图片
如何批量快速提取出PDF中的图片文件,你是否遇到这样的一个问题,尤其是PPT文件转换为PDF文件,需要快速提取其中的图片文件,如果你恰好会那么一点py,同时复制粘贴没问题的话,那么相信你也能够很轻松的 ...
- 如何从PDF文件中快速的提取PDF文件
现在网上有很多文案或者文章都是pdf文件格式的,我们想借鉴里面的案例做成PPT,但是里面的图片就是提取不出来的,这里小编要说的是PDF文件提取不出来是正常的,pdf文件是个将图片.文字.超链接.声音等 ...
- 使用PyPDF4和PIL修改PDF文件中的图片
继上篇从PDF中提取图片数据之后,我们看如何使用PIL修改图片并写入到PDF文件. 先放两个相关链接: 使用PyPDF4提取pdf文件中的图片 PIL从内存中加载图片 先放代码: import PyP ...
- 如何用迅捷PDF转换器获取PDF文件中的图片
工作中有的人喜欢将文档保存为PDF格式,因为PDF格式安全性和兼容性都比较高,但是在使用PDF文档的时候,也会一些小问题,比如说,PDF文档过大,想要查看文档中的图片,就需要耗费不少的时间,那么怎么才 ...
- PDF文件中的图片如何删除?分享两种删除方法
我们怎么把PDF文件中的图片给删除掉呢?大家在日常使用PDF文件的过程中,难免会对文件有编辑需求,有时候需要编辑文字,有时候需要对文件中的图片进行删除处理.遇到这种只需要删除PDF文件里的图片的时候, ...
- 如何快速在PDF文件中插入图片
在 PDF文件中插入图片我优先想到了 Adobe Acrobat DC,胜任此项工作完全 OK.但是有个问题,Acrobat 会自动识别 PDF 中的文字.如果有手写字迹经过 Acrobat 识别再保 ...
- 向pdf文件中插入图片及文字 java实现
向pdf文件中插入图片及文字 引入itextpdf相关依赖 <!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf --> ...
- PDF文件中的图片怎么导出?
我们经常使用PDF文档.我们都知道,PDF文档在阅读方面的体验非常的好,但是想使用PDF文件内的内容却很难,由于PDF可以固定文档的页面布局,因此无法直接保存PDF文档中的内容.我们在阅读PDF文件内 ...
最新文章
- 渥太华大学计算机工程,渥太华大学电气与计算机工程硕士专业.pdf
- 阿里:马云从未转让和退出淘宝股份 也没有这个打算
- mysql中使用HAVING 筛选分组后的数据
- [蓝桥杯2018初赛]递增三元组-双指针,枚举,排序,前缀和
- Pycharm使用远程服务器运行代码
- android 京东白条支付,京东网银钱包安卓版上线:整合京东白条和小金库
- Servlet验证码功能
- Python学习入门8:新人怎么学习Python
- c语言的44种运算符,C语言重要知识点总结【9】:C语言运算符(详解)
- 浏览器桌面通知(notifications)
- 分组取出值最大的数据
- VS2015sql本地服务器为空,详解VS2015自带LocalDB数据库用法实例
- JAVA封装,继承,多态详解
- Jquery头像编辑器
- 【电信学】【2019.07】基于ATOLL的5G网络规划与优化
- android manifest 多个application,Android - 如何避免多個Manifest文件中的重復?
- java itextpdf 5 基础知识
- Bootstrap基本结构
- 关于烧饼游戏修改器的分析
- 零基础计算机英语教程,零基础学英语语法的方法