(py-indent-right, py-outdent-left): new commands, bound to C-c C-r and
[python/dscho.git] / Lib / imghdr.py
blob62518b5f36c9b9400d75364483c1da9dd0650996
1 # Recognizing image files based on their first few bytes.
4 #-------------------------#
5 # Recognize sound headers #
6 #-------------------------#
8 def what(filename):
9 f = open(filename, 'r')
10 h = f.read(32)
11 for tf in tests:
12 res = tf(h, f)
13 if res:
14 return res
15 return None
18 #---------------------------------#
19 # Subroutines per image file type #
20 #---------------------------------#
22 tests = []
24 def test_rgb(h, f):
25 # SGI image library
26 if h[:2] == '\001\332':
27 return 'rgb'
29 tests.append(test_rgb)
31 def test_gif(h, f):
32 # GIF ('87 and '89 variants)
33 if h[:6] in ('GIF87a', 'GIF89a'):
34 return 'gif'
36 tests.append(test_gif)
38 def test_pbm(h, f):
39 # PBM (portable bitmap)
40 if len(h) >= 3 and \
41 h[0] == 'P' and h[1] in '14' and h[2] in ' \t\n\r':
42 return 'pbm'
44 tests.append(test_pbm)
46 def test_pgm(h, f):
47 # PGM (portable graymap)
48 if len(h) >= 3 and \
49 h[0] == 'P' and h[1] in '25' and h[2] in ' \t\n\r':
50 return 'pgm'
52 tests.append(test_pgm)
54 def test_ppm(h, f):
55 # PPM (portable pixmap)
56 if len(h) >= 3 and \
57 h[0] == 'P' and h[1] in '36' and h[2] in ' \t\n\r':
58 return 'ppm'
60 tests.append(test_ppm)
62 def test_tiff(h, f):
63 # TIFF (can be in Motorola or Intel byte order)
64 if h[:2] in ('MM', 'II'):
65 return 'tiff'
67 tests.append(test_tiff)
69 def test_rast(h, f):
70 # Sun raster file
71 if h[:4] == '\x59\xA6\x6A\x95':
72 return 'rast'
74 tests.append(test_rast)
76 def test_xbm(h, f):
77 # X bitmap (X10 or X11)
78 s = '#define '
79 if h[:len(s)] == s:
80 return 'xbm'
82 tests.append(test_xbm)
84 def test_jpeg(h, f):
85 # JPEG data in JFIF format
86 if h[6:10] == 'JFIF':
87 return 'jpeg'
89 tests.append(test_jpeg)
91 #--------------------#
92 # Small test program #
93 #--------------------#
95 def test():
96 import sys
97 recursive = 0
98 if sys.argv[1:] and sys.argv[1] == '-r':
99 del sys.argv[1:2]
100 recursive = 1
101 try:
102 if sys.argv[1:]:
103 testall(sys.argv[1:], recursive, 1)
104 else:
105 testall(['.'], recursive, 1)
106 except KeyboardInterrupt:
107 sys.stderr.write('\n[Interrupted]\n')
108 sys.exit(1)
110 def testall(list, recursive, toplevel):
111 import sys
112 import os
113 for filename in list:
114 if os.path.isdir(filename):
115 print filename + '/:',
116 if recursive or toplevel:
117 print 'recursing down:'
118 import glob
119 names = glob.glob(os.path.join(filename, '*'))
120 testall(names, recursive, 0)
121 else:
122 print '*** directory (use -r) ***'
123 else:
124 print filename + ':',
125 sys.stdout.flush()
126 try:
127 print what(filename)
128 except IOError:
129 print '*** not found ***'