home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / pyth_os2.zip / python-1.0.2 / Demo / sgi / cl / rgbtojpeg.py < prev   
Text File  |  1993-02-19  |  2KB  |  73 lines

  1. # Compress an RGB image using JPEG.
  2. #
  3. # This program shows how to use the Compression Library to compress an
  4. # RGB image with JPEG.
  5. #
  6. # An alternative way of compressing would be to use CompressImage(),
  7. # but since the order of the scan lines in an RGB file is
  8. # bottom-to-top and in a JPEG image top-to-bottom, we need to use the
  9. # CL.ORIENTATION parameter.  This cannot be done using
  10. # CompressImage().  The call would be:
  11. # data = cl.CompressImage(CL.JPEG, width, height, orig, 15.0, iamge)
  12.  
  13. Error = 'rgbtojpeg.error'
  14.  
  15. def readrgb(file):
  16.     import imgfile
  17.  
  18.     width, height, depth = imgfile.getsizes(file)
  19.     data = imgfile.read(file)
  20.     return width, height, depth, data
  21.  
  22. def cjpeg(width, height, depth, image, quality):
  23.     import cl, CL
  24.  
  25.     if depth == 3:
  26.         orig = CL.RGBX
  27.     elif depth == 1:
  28.         orig = CL.RGB332
  29.     elif depth == 4:
  30.         orig = CL.RGBA
  31.     else:
  32.         raise Error, 'unrecognized depth'
  33.     params = [CL.ORIGINAL_FORMAT, orig, \
  34.           CL.ORIENTATION, CL.BOTTOM_UP, \
  35.           CL.IMAGE_WIDTH, width, \
  36.           CL.IMAGE_HEIGHT, height, \
  37.           CL.QUALITY_FACTOR, quality]
  38.     comp = cl.OpenCompressor(CL.JPEG)
  39.     comp.SetParams(params)
  40.     data = comp.Compress(1, image)
  41.     comp.CloseCompressor()
  42.     return data
  43.  
  44. def main():
  45.     usage = 'cjpeg [-Q quality] filename [outfilename]'
  46.     import sys, getopt
  47.     try:
  48.         options, args = getopt.getopt(sys.argv[1:], 'Q:')
  49.     except getopt.error:
  50.         print usage
  51.         sys.exit(2)
  52.     quality = 75
  53.     for argpair in options:
  54.         import string
  55.         if argpair[0] == '-Q':
  56.             try:
  57.                 quality = string.atoi(argpair[1])
  58.             except string.atoi_error:
  59.                 print usage
  60.                 sys.exit(2)
  61.     if len(args) not in (1, 2):
  62.         print usage
  63.         sys.exit(2)
  64.     if len(args) == 2:
  65.         outfile = open(args[1], 'w')
  66.     else:
  67.         outfile = sys.stdout
  68.  
  69.     width, height, depth, image = readrgb(args[0])
  70.     outfile.write(cjpeg(width, height, depth, image, quality))
  71.  
  72. main()
  73.