1 # Implement 'jpeg' interface using SGI's compression library
3 # XXX Options 'smooth' and 'optimize' are ignored.
5 # XXX It appears that compressing grayscale images doesn't work right;
6 # XXX the resulting file causes weirdness.
8 class error(Exception):
11 options
= {'quality': 75, 'optimize': 0, 'smooth': 0, 'forcegray': 0}
16 def compress(imgdata
, width
, height
, bytesperpixel
):
19 if comp
is None: comp
= cl
.OpenCompressor(cl
.JPEG
)
20 if bytesperpixel
== 1:
22 elif bytesperpixel
== 4:
24 if options
['forcegray']:
25 iformat
= cl
.GRAYSCALE
28 # XXX How to support 'optimize'?
29 params
= [cl
.IMAGE_WIDTH
, width
, cl
.IMAGE_HEIGHT
, height
,
30 cl
.ORIGINAL_FORMAT
, format
,
31 cl
.ORIENTATION
, cl
.BOTTOM_UP
,
32 cl
.QUALITY_FACTOR
, options
['quality'],
33 cl
.INTERNAL_FORMAT
, iformat
,
35 comp
.SetParams(params
)
36 jpegdata
= comp
.Compress(1, imgdata
)
39 def decompress(jpegdata
):
42 if decomp
is None: decomp
= cl
.OpenDecompressor(cl
.JPEG
)
43 headersize
= decomp
.ReadHeader(jpegdata
)
44 params
= [cl
.IMAGE_WIDTH
, 0, cl
.IMAGE_HEIGHT
, 0, cl
.INTERNAL_FORMAT
, 0]
45 decomp
.GetParams(params
)
46 width
, height
, format
= params
[1], params
[3], params
[5]
47 if format
== cl
.GRAYSCALE
or options
['forcegray']:
53 # XXX How to support 'smooth'?
54 params
= [cl
.ORIGINAL_FORMAT
, format
,
55 cl
.ORIENTATION
, cl
.BOTTOM_UP
,
56 cl
.FRAME_BUFFER_SIZE
, width
*height
*bytesperpixel
]
57 decomp
.SetParams(params
)
58 imgdata
= decomp
.Decompress(1, jpegdata
)
59 return imgdata
, width
, height
, bytesperpixel
61 def setoption(name
, value
):
62 if type(value
) is not type(0):
63 raise TypeError, 'jpeg.setoption: numeric options only'
64 if name
== 'forcegrey':
66 if not options
.has_key(name
):
67 raise KeyError, 'jpeg.setoption: unknown option name'
68 options
[name
] = int(value
)
72 if sys
.argv
[1:2] == ['-g']:
74 setoption('forcegray', 1)
76 sys
.argv
.append('/usr/local/images/data/jpg/asterix.jpg')
77 for file in sys
.argv
[1:]:
82 jpegdata
= open(file, 'r').read()
83 imgdata
, width
, height
, bytesperpixel
= decompress(jpegdata
)
85 gl
.prefsize(width
, height
)
86 win
= gl
.winopen(file)
87 if bytesperpixel
== 1:
89 gl
.pixmode(GL
.PM_SIZE
, 8)
92 gl
.mapcolor(i
, i
, i
, i
)
95 gl
.pixmode(GL
.PM_SIZE
, 32)
97 gl
.qdevice(DEVICE
.REDRAW
)
98 gl
.qdevice(DEVICE
.ESCKEY
)
99 gl
.qdevice(DEVICE
.WINQUIT
)
100 gl
.qdevice(DEVICE
.WINSHUT
)
101 gl
.lrectwrite(0, 0, width
-1, height
-1, imgdata
)
103 dev
, val
= gl
.qread()
104 if dev
in (DEVICE
.ESCKEY
, DEVICE
.WINSHUT
, DEVICE
.WINQUIT
):
106 if dev
== DEVICE
.REDRAW
:
107 gl
.lrectwrite(0, 0, width
-1, height
-1, imgdata
)
109 # Now test the compression and write the result to a fixed filename
110 newjpegdata
= compress(imgdata
, width
, height
, bytesperpixel
)
111 open('/tmp/j.jpg', 'w').write(newjpegdata
)