pilconvert.py 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. #!/home/daccorsi/sources/protos/pboard/tg2env/bin/python
  2. #
  3. # The Python Imaging Library.
  4. # $Id$
  5. #
  6. # convert image files
  7. #
  8. # History:
  9. # 0.1 96-04-20 fl Created
  10. # 0.2 96-10-04 fl Use draft mode when converting images
  11. # 0.3 96-12-30 fl Optimize output (PNG, JPEG)
  12. # 0.4 97-01-18 fl Made optimize an option (PNG, JPEG)
  13. # 0.5 98-12-30 fl Fixed -f option (from Anthony Baxter)
  14. #
  15. import site
  16. import getopt, string, sys
  17. from PIL import Image
  18. def usage():
  19. print "PIL Convert 0.5/1998-12-30 -- convert image files"
  20. print "Usage: pilconvert [option] infile outfile"
  21. print
  22. print "Options:"
  23. print
  24. print " -c <format> convert to format (default is given by extension)"
  25. print
  26. print " -g convert to greyscale"
  27. print " -p convert to palette image (using standard palette)"
  28. print " -r convert to rgb"
  29. print
  30. print " -o optimize output (trade speed for size)"
  31. print " -q <value> set compression quality (0-100, JPEG only)"
  32. print
  33. print " -f list supported file formats"
  34. sys.exit(1)
  35. if len(sys.argv) == 1:
  36. usage()
  37. try:
  38. opt, argv = getopt.getopt(sys.argv[1:], "c:dfgopq:r")
  39. except getopt.error, v:
  40. print v
  41. sys.exit(1)
  42. format = None
  43. convert = None
  44. options = { }
  45. for o, a in opt:
  46. if o == "-f":
  47. Image.init()
  48. id = Image.ID[:]
  49. id.sort()
  50. print "Supported formats (* indicates output format):"
  51. for i in id:
  52. if Image.SAVE.has_key(i):
  53. print i+"*",
  54. else:
  55. print i,
  56. sys.exit(1)
  57. elif o == "-c":
  58. format = a
  59. if o == "-g":
  60. convert = "L"
  61. elif o == "-p":
  62. convert = "P"
  63. elif o == "-r":
  64. convert = "RGB"
  65. elif o == "-o":
  66. options["optimize"] = 1
  67. elif o == "-q":
  68. options["quality"] = string.atoi(a)
  69. if len(argv) != 2:
  70. usage()
  71. try:
  72. im = Image.open(argv[0])
  73. if convert and im.mode != convert:
  74. im.draft(convert, im.size)
  75. im = im.convert(convert)
  76. if format:
  77. apply(im.save, (argv[1], format), options)
  78. else:
  79. apply(im.save, (argv[1],), options)
  80. except:
  81. print "cannot convert image",
  82. print "(%s:%s)" % (sys.exc_type, sys.exc_value)