blob: e46aca33cef4813d6c494e240c0a29350dcbdb19 [file] [log] [blame]
Guido van Rossum2db91351992-10-18 17:09:59 +00001# Convert "arbitrary" image files to rgb files (SGI's image format).
2# Input may be compressed.
3# The uncompressed file type may be PBM, PGM, PPM, GIF, TIFF, or Sun raster.
4# An exception is raised if the file is not of a recognized type.
5# Returned filename is either the input filename or a temporary filename;
6# in the latter case the caller must ensure that it is removed.
7# Other temporary files used are removed by the function.
8
9import os
10import tempfile
11import pipes
12import imghdr
13
14table = {}
15
16t = pipes.Template().init()
17t.append('fromppm $IN $OUT', 'ff')
18table['ppm'] = t
19
20t = pipes.Template().init()
21t.append('pnmtoppm', '--')
22t.append('fromppm $IN $OUT', 'ff')
23table['pnm'] = t
24table['pgm'] = t
25table['pbm'] = t
26
27t = pipes.Template().init()
28t.append('fromgif $IN $OUT', 'ff')
29table['gif'] = t
30
31t = pipes.Template().init()
32t.append('tifftopnm', '--')
33t.append('(PATH=$PATH:/ufs/guido/bin/sgi; exec pnmtoppm)', '--')
34t.append('fromppm $IN $OUT', 'ff')
35table['tiff'] = t
36
37t = pipes.Template().init()
38t.append('rasttopnm', '--')
39t.append('pnmtoppm', '--')
40t.append('fromppm $IN $OUT', 'ff')
41table['rast'] = t
42
43uncompress = pipes.Template().init()
44uncompress.append('uncompress', '--')
45
46
47error = 'torgb.error' # Exception
48
49def torgb(filename):
50 temps = []
51 ret = None
52 try:
53 ret = _torgb(filename, temps)
54 finally:
55 for temp in temps[:]:
56 if temp <> ret:
57 try:
58 os.unlink(temp)
59 except os.error:
60 pass
61 temps.remove(temp)
62 return ret
63
64def _torgb(filename, temps):
65 if filename[-2:] == '.Z':
66 fname = tempfile.mktemp()
67 temps.append(fname)
68 sts = uncompress.copy(filename, fname)
69 if sts:
70 raise error, filename + ': uncompress failed'
71 else:
72 fname = filename
73 try:
74 ftype = imghdr.what(fname)
75 except IOError, msg:
76 if type(msg) == type(()) and len(msg) == 2 and \
77 type(msg[0]) == type(0) and type(msg[1]) == type(''):
78 msg = msg[1]
79 if type(msg) <> type(''):
80 msg = `msg`
81 raise error, filename + ': ' + msg
82 if ftype == 'rgb':
83 return fname
84 if ftype == None or not table.has_key(ftype):
85 raise error, \
86 filename + ': unsupported image file type ' + `ftype`
87 temp = tempfile.mktemp()
88 sts = table[ftype].copy(fname, temp)
89 if sts:
90 raise error, filename + ': conversion to rgb failed'
91 return temp