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 error
= 'jpeg.error' # Exception
10 options
= {'quality': 75, 'optimize': 0, 'smooth': 0, 'forcegray': 0}
15 def compress(imgdata
, width
, height
, bytesperpixel
):
18 if comp
is None: comp
= cl
.OpenCompressor(cl
.JPEG
)
19 if bytesperpixel
== 1:
21 elif bytesperpixel
== 4:
23 if options
['forcegray']:
24 iformat
= cl
.GRAYSCALE
27 # XXX How to support 'optimize'?
28 params
= [cl
.IMAGE_WIDTH
, width
, cl
.IMAGE_HEIGHT
, height
,
29 cl
.ORIGINAL_FORMAT
, format
,
30 cl
.ORIENTATION
, cl
.BOTTOM_UP
,
31 cl
.QUALITY_FACTOR
, options
['quality'],
32 cl
.INTERNAL_FORMAT
, iformat
,
34 comp
.SetParams(params
)
35 jpegdata
= comp
.Compress(1, imgdata
)
38 def decompress(jpegdata
):
41 if decomp
is None: decomp
= cl
.OpenDecompressor(cl
.JPEG
)
42 headersize
= decomp
.ReadHeader(jpegdata
)
43 params
= [cl
.IMAGE_WIDTH
, 0, cl
.IMAGE_HEIGHT
, 0, cl
.INTERNAL_FORMAT
, 0]
44 decomp
.GetParams(params
)
45 width
, height
, format
= params
[1], params
[3], params
[5]
46 if format
== cl
.GRAYSCALE
or options
['forcegray']:
52 # XXX How to support 'smooth'?
53 params
= [cl
.ORIGINAL_FORMAT
, format
,
54 cl
.ORIENTATION
, cl
.BOTTOM_UP
,
55 cl
.FRAME_BUFFER_SIZE
, width
*height
*bytesperpixel
]
56 decomp
.SetParams(params
)
57 imgdata
= decomp
.Decompress(1, jpegdata
)
58 return imgdata
, width
, height
, bytesperpixel
60 def setoption(name
, value
):
61 if type(value
) <> type(0):
62 raise TypeError, 'jpeg.setoption: numeric options only'
63 if name
== 'forcegrey':
65 if not options
.has_key(name
):
66 raise KeyError, 'jpeg.setoption: unknown option name'
67 options
[name
] = int(value
)
71 if sys
.argv
[1:2] == ['-g']:
73 setoption('forcegray', 1)
75 sys
.argv
.append('/usr/local/images/data/jpg/asterix.jpg')
76 for file in sys
.argv
[1:]:
81 jpegdata
= open(file, 'r').read()
82 imgdata
, width
, height
, bytesperpixel
= decompress(jpegdata
)
84 gl
.prefsize(width
, height
)
85 win
= gl
.winopen(file)
86 if bytesperpixel
== 1:
88 gl
.pixmode(GL
.PM_SIZE
, 8)
91 gl
.mapcolor(i
, i
, i
, i
)
94 gl
.pixmode(GL
.PM_SIZE
, 32)
96 gl
.qdevice(DEVICE
.REDRAW
)
97 gl
.qdevice(DEVICE
.ESCKEY
)
98 gl
.qdevice(DEVICE
.WINQUIT
)
99 gl
.qdevice(DEVICE
.WINSHUT
)
100 gl
.lrectwrite(0, 0, width
-1, height
-1, imgdata
)
102 dev
, val
= gl
.qread()
103 if dev
in (DEVICE
.ESCKEY
, DEVICE
.WINSHUT
, DEVICE
.WINQUIT
):
105 if dev
== DEVICE
.REDRAW
:
106 gl
.lrectwrite(0, 0, width
-1, height
-1, imgdata
)
108 # Now test the compression and write the result to a fixed filename
109 newjpegdata
= compress(imgdata
, width
, height
, bytesperpixel
)
110 open('/tmp/j.jpg', 'w').write(newjpegdata
)