Guido van Rossum | 1c34fc7 | 1992-05-27 14:06:59 +0000 | [diff] [blame^] | 1 | # Recognizing image files based on their first few bytes. |
| 2 | |
| 3 | |
| 4 | #-------------------------# |
| 5 | # Recognize sound headers # |
| 6 | #-------------------------# |
| 7 | |
| 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 |
| 16 | |
| 17 | |
| 18 | #---------------------------------# |
| 19 | # Subroutines per image file type # |
| 20 | #---------------------------------# |
| 21 | |
| 22 | tests = [] |
| 23 | |
| 24 | def test_rgb(h, f): |
| 25 | # SGI image library |
| 26 | if h[:2] == '\001\332': |
| 27 | return 'rgb' |
| 28 | |
| 29 | tests.append(test_rgb) |
| 30 | |
| 31 | def test_gif(h, f): |
| 32 | # GIF ('87 and '89 variants) |
| 33 | if h[:6] in ('GIF87a', 'GIF89a'): |
| 34 | return 'gif' |
| 35 | |
| 36 | tests.append(test_gif) |
| 37 | |
| 38 | def test_pnm(h, f): |
| 39 | # PBM, PGM, PPM (portable {bit,gray,pix}map; together portable anymap) |
| 40 | if h[0] == 'P' and h[1] in '123456' and h[2] in ' \t\n\r': |
| 41 | return 'pnm' |
| 42 | |
| 43 | tests.append(test_pnm) |
| 44 | |
| 45 | def test_tiff(h, f): |
| 46 | # TIFF (can be in Motorola or Intel byte order) |
| 47 | if h[:2] in ('MM', 'II'): |
| 48 | return 'tiff' |
| 49 | |
| 50 | tests.append(test_tiff) |
| 51 | |
| 52 | def test_rast(h, f): |
| 53 | # Sun raster file |
| 54 | if h[:4] == '\x59\xA6\x6A\x95': |
| 55 | return 'rast' |
| 56 | |
| 57 | tests.append(test_rast) |
| 58 | |
| 59 | |
| 60 | #--------------------# |
| 61 | # Small test program # |
| 62 | #--------------------# |
| 63 | |
| 64 | def test(): |
| 65 | import sys |
| 66 | recursive = 0 |
| 67 | if sys.argv[1:] and sys.argv[1] == '-r': |
| 68 | del sys.argv[1:2] |
| 69 | recursive = 1 |
| 70 | try: |
| 71 | if sys.argv[1:]: |
| 72 | testall(sys.argv[1:], recursive, 1) |
| 73 | else: |
| 74 | testall(['.'], recursive, 1) |
| 75 | except KeyboardInterrupt: |
| 76 | sys.stderr.write('\n[Interrupted]\n') |
| 77 | sys.exit(1) |
| 78 | |
| 79 | def testall(list, recursive, toplevel): |
| 80 | import sys |
| 81 | import os |
| 82 | for filename in list: |
| 83 | if os.path.isdir(filename): |
| 84 | print filename + '/:', |
| 85 | if recursive or toplevel: |
| 86 | print 'recursing down:' |
| 87 | import glob |
| 88 | names = glob.glob(os.path.join(filename, '*')) |
| 89 | testall(names, recursive, 0) |
| 90 | else: |
| 91 | print '*** directory (use -r) ***' |
| 92 | else: |
| 93 | print filename + ':', |
| 94 | sys.stdout.flush() |
| 95 | try: |
| 96 | print what(filename) |
| 97 | except IOError: |
| 98 | print '*** not found ***' |