Contents
提取文档中的图象标识信息
Shuguang Yang <[email protected]> reply-to [email protected] to python-cn`CPyUG`华蟒用户组 <[email protected]> date Wed, Aug 20, 2008 at 15:50 subject [CPyUG:62863] 用python提取文档中的图象,图象的标识信息
应用 Python 解决一些实际问题(
的提取嵌入在文档中的图像部分,原文中的程序思路正确但代码不够简洁,不够pythonic。 改进后的代码如下:
1 import sys
2 import os
3 import string
4 headers = [('JFIF', 6, 'jpg'), ('GIF', 0, 'gif'), ('PNG', 1, 'png')] #不同图片格式的标识信息
5 marker = []
6 filename = '/path/to/your/file'
7 try:
8 fid = open(filename, 'rb')
9 except:
10 sys.exit(1)
11 s = 0
12 for line in fid: #按行迭代
13 for flag, offset, ext in headers:
14 index = string.find(line, flag)
15 if index > 0:
16 pos = s + index - offset
17 marker.append((pos, ext))
18 s += len(line)
19 fid.seek(0)
20 imgnum = 0
21 if len(marker) == 0:
22 print 'No images included in this document'
23 sys.exit(1)
24 for info in marker:
25 thispos = info[0]
26 thisext = info[1]
27 index = marker.index(info)
28 try:
29 nextinfo = marker[index + 1]
30 nextpos = nextinfo[0]
31 gap = nextpos - thispos
32 except IndexError:
33 nextpos = s
34 gap = nextpos - thispos
35 fid.seek(thispos)
36 data = fid.read(gap)
37 imgname = 'imgname%02d.%s' % (index, thisext)
38 fid1 = open(imgname, 'wb')
39 fid1.write(data)
40 fid1.close()
41 imgnum += 1
42 fid.close()
43 print '%02d images have been extracted' % imgnum
反馈
创建 by -- ZoomQuiet [2008-08-20 07:55:11]