ImageMode.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #
  2. # The Python Imaging Library.
  3. # $Id$
  4. #
  5. # standard mode descriptors
  6. #
  7. # History:
  8. # 2006-03-20 fl Added
  9. #
  10. # Copyright (c) 2006 by Secret Labs AB.
  11. # Copyright (c) 2006 by Fredrik Lundh.
  12. #
  13. # See the README file for information on usage and redistribution.
  14. #
  15. import sys
  16. # mode descriptor cache
  17. _modes = None
  18. class ModeDescriptor:
  19. """Wrapper for mode strings."""
  20. def __init__(self, mode, bands, basemode, basetype, typestr):
  21. self.mode = mode
  22. self.bands = bands
  23. self.basemode = basemode
  24. self.basetype = basetype
  25. self.typestr = typestr
  26. def __str__(self):
  27. return self.mode
  28. def getmode(mode):
  29. """Gets a mode descriptor for the given mode."""
  30. global _modes
  31. if not _modes:
  32. # initialize mode cache
  33. modes = {}
  34. endian = "<" if sys.byteorder == "little" else ">"
  35. for m, (basemode, basetype, bands, typestr) in {
  36. # core modes
  37. # Bits need to be extended to bytes
  38. "1": ("L", "L", ("1",), "|b1"),
  39. "L": ("L", "L", ("L",), "|u1"),
  40. "I": ("L", "I", ("I",), endian + "i4"),
  41. "F": ("L", "F", ("F",), endian + "f4"),
  42. "P": ("P", "L", ("P",), "|u1"),
  43. "RGB": ("RGB", "L", ("R", "G", "B"), "|u1"),
  44. "RGBX": ("RGB", "L", ("R", "G", "B", "X"), "|u1"),
  45. "RGBA": ("RGB", "L", ("R", "G", "B", "A"), "|u1"),
  46. "CMYK": ("RGB", "L", ("C", "M", "Y", "K"), "|u1"),
  47. "YCbCr": ("RGB", "L", ("Y", "Cb", "Cr"), "|u1"),
  48. # UNDONE - unsigned |u1i1i1
  49. "LAB": ("RGB", "L", ("L", "A", "B"), "|u1"),
  50. "HSV": ("RGB", "L", ("H", "S", "V"), "|u1"),
  51. # extra experimental modes
  52. "RGBa": ("RGB", "L", ("R", "G", "B", "a"), "|u1"),
  53. "BGR;15": ("RGB", "L", ("B", "G", "R"), "|u1"),
  54. "BGR;16": ("RGB", "L", ("B", "G", "R"), "|u1"),
  55. "BGR;24": ("RGB", "L", ("B", "G", "R"), "|u1"),
  56. "LA": ("L", "L", ("L", "A"), "|u1"),
  57. "La": ("L", "L", ("L", "a"), "|u1"),
  58. "PA": ("RGB", "L", ("P", "A"), "|u1"),
  59. }.items():
  60. modes[m] = ModeDescriptor(m, bands, basemode, basetype, typestr)
  61. # mapping modes
  62. for i16mode, typestr in {
  63. # I;16 == I;16L, and I;32 == I;32L
  64. "I;16": "<u2",
  65. "I;16S": "<i2",
  66. "I;16L": "<u2",
  67. "I;16LS": "<i2",
  68. "I;16B": ">u2",
  69. "I;16BS": ">i2",
  70. "I;16N": endian + "u2",
  71. "I;16NS": endian + "i2",
  72. "I;32": "<u4",
  73. "I;32B": ">u4",
  74. "I;32L": "<u4",
  75. "I;32S": "<i4",
  76. "I;32BS": ">i4",
  77. "I;32LS": "<i4",
  78. }.items():
  79. modes[i16mode] = ModeDescriptor(i16mode, ("I",), "L", "L", typestr)
  80. # set global mode cache atomically
  81. _modes = modes
  82. return _modes[mode]