/Lib/plat-mac/PixMapWrapper.py

http://unladen-swallow.googlecode.com/ · Python · 218 lines · 163 code · 19 blank · 36 comment · 28 complexity · 7512e5893641fefaaa66dca537f45582 MD5 · raw file

  1. """PixMapWrapper - defines the PixMapWrapper class, which wraps an opaque
  2. QuickDraw PixMap data structure in a handy Python class. Also provides
  3. methods to convert to/from pixel data (from, e.g., the img module) or a
  4. Python Imaging Library Image object.
  5. J. Strout <joe@strout.net> February 1999"""
  6. from warnings import warnpy3k
  7. warnpy3k("In 3.x, the PixMapWrapper module is removed.", stacklevel=2)
  8. from Carbon import Qd
  9. from Carbon import QuickDraw
  10. import struct
  11. import MacOS
  12. import img
  13. import imgformat
  14. # PixMap data structure element format (as used with struct)
  15. _pmElemFormat = {
  16. 'baseAddr':'l', # address of pixel data
  17. 'rowBytes':'H', # bytes per row, plus 0x8000
  18. 'bounds':'hhhh', # coordinates imposed over pixel data
  19. 'top':'h',
  20. 'left':'h',
  21. 'bottom':'h',
  22. 'right':'h',
  23. 'pmVersion':'h', # flags for Color QuickDraw
  24. 'packType':'h', # format of compression algorithm
  25. 'packSize':'l', # size after compression
  26. 'hRes':'l', # horizontal pixels per inch
  27. 'vRes':'l', # vertical pixels per inch
  28. 'pixelType':'h', # pixel format
  29. 'pixelSize':'h', # bits per pixel
  30. 'cmpCount':'h', # color components per pixel
  31. 'cmpSize':'h', # bits per component
  32. 'planeBytes':'l', # offset in bytes to next plane
  33. 'pmTable':'l', # handle to color table
  34. 'pmReserved':'l' # reserved for future use
  35. }
  36. # PixMap data structure element offset
  37. _pmElemOffset = {
  38. 'baseAddr':0,
  39. 'rowBytes':4,
  40. 'bounds':6,
  41. 'top':6,
  42. 'left':8,
  43. 'bottom':10,
  44. 'right':12,
  45. 'pmVersion':14,
  46. 'packType':16,
  47. 'packSize':18,
  48. 'hRes':22,
  49. 'vRes':26,
  50. 'pixelType':30,
  51. 'pixelSize':32,
  52. 'cmpCount':34,
  53. 'cmpSize':36,
  54. 'planeBytes':38,
  55. 'pmTable':42,
  56. 'pmReserved':46
  57. }
  58. class PixMapWrapper:
  59. """PixMapWrapper -- wraps the QD PixMap object in a Python class,
  60. with methods to easily get/set various pixmap fields. Note: Use the
  61. PixMap() method when passing to QD calls."""
  62. def __init__(self):
  63. self.__dict__['data'] = ''
  64. self._header = struct.pack("lhhhhhhhlllhhhhlll",
  65. id(self.data)+MacOS.string_id_to_buffer,
  66. 0, # rowBytes
  67. 0, 0, 0, 0, # bounds
  68. 0, # pmVersion
  69. 0, 0, # packType, packSize
  70. 72<<16, 72<<16, # hRes, vRes
  71. QuickDraw.RGBDirect, # pixelType
  72. 16, # pixelSize
  73. 2, 5, # cmpCount, cmpSize,
  74. 0, 0, 0) # planeBytes, pmTable, pmReserved
  75. self.__dict__['_pm'] = Qd.RawBitMap(self._header)
  76. def _stuff(self, element, bytes):
  77. offset = _pmElemOffset[element]
  78. fmt = _pmElemFormat[element]
  79. self._header = self._header[:offset] \
  80. + struct.pack(fmt, bytes) \
  81. + self._header[offset + struct.calcsize(fmt):]
  82. self.__dict__['_pm'] = None
  83. def _unstuff(self, element):
  84. offset = _pmElemOffset[element]
  85. fmt = _pmElemFormat[element]
  86. return struct.unpack(fmt, self._header[offset:offset+struct.calcsize(fmt)])[0]
  87. def __setattr__(self, attr, val):
  88. if attr == 'baseAddr':
  89. raise 'UseErr', "don't assign to .baseAddr -- assign to .data instead"
  90. elif attr == 'data':
  91. self.__dict__['data'] = val
  92. self._stuff('baseAddr', id(self.data) + MacOS.string_id_to_buffer)
  93. elif attr == 'rowBytes':
  94. # high bit is always set for some odd reason
  95. self._stuff('rowBytes', val | 0x8000)
  96. elif attr == 'bounds':
  97. # assume val is in official Left, Top, Right, Bottom order!
  98. self._stuff('left',val[0])
  99. self._stuff('top',val[1])
  100. self._stuff('right',val[2])
  101. self._stuff('bottom',val[3])
  102. elif attr == 'hRes' or attr == 'vRes':
  103. # 16.16 fixed format, so just shift 16 bits
  104. self._stuff(attr, int(val) << 16)
  105. elif attr in _pmElemFormat.keys():
  106. # any other pm attribute -- just stuff
  107. self._stuff(attr, val)
  108. else:
  109. self.__dict__[attr] = val
  110. def __getattr__(self, attr):
  111. if attr == 'rowBytes':
  112. # high bit is always set for some odd reason
  113. return self._unstuff('rowBytes') & 0x7FFF
  114. elif attr == 'bounds':
  115. # return bounds in official Left, Top, Right, Bottom order!
  116. return ( \
  117. self._unstuff('left'),
  118. self._unstuff('top'),
  119. self._unstuff('right'),
  120. self._unstuff('bottom') )
  121. elif attr == 'hRes' or attr == 'vRes':
  122. # 16.16 fixed format, so just shift 16 bits
  123. return self._unstuff(attr) >> 16
  124. elif attr in _pmElemFormat.keys():
  125. # any other pm attribute -- just unstuff
  126. return self._unstuff(attr)
  127. else:
  128. return self.__dict__[attr]
  129. def PixMap(self):
  130. "Return a QuickDraw PixMap corresponding to this data."
  131. if not self.__dict__['_pm']:
  132. self.__dict__['_pm'] = Qd.RawBitMap(self._header)
  133. return self.__dict__['_pm']
  134. def blit(self, x1=0,y1=0,x2=None,y2=None, port=None):
  135. """Draw this pixmap into the given (default current) grafport."""
  136. src = self.bounds
  137. dest = [x1,y1,x2,y2]
  138. if x2 is None:
  139. dest[2] = x1 + src[2]-src[0]
  140. if y2 is None:
  141. dest[3] = y1 + src[3]-src[1]
  142. if not port: port = Qd.GetPort()
  143. Qd.CopyBits(self.PixMap(), port.GetPortBitMapForCopyBits(), src, tuple(dest),
  144. QuickDraw.srcCopy, None)
  145. def fromstring(self,s,width,height,format=imgformat.macrgb):
  146. """Stuff this pixmap with raw pixel data from a string.
  147. Supply width, height, and one of the imgformat specifiers."""
  148. # we only support 16- and 32-bit mac rgb...
  149. # so convert if necessary
  150. if format != imgformat.macrgb and format != imgformat.macrgb16:
  151. # (LATER!)
  152. raise "NotImplementedError", "conversion to macrgb or macrgb16"
  153. self.data = s
  154. self.bounds = (0,0,width,height)
  155. self.cmpCount = 3
  156. self.pixelType = QuickDraw.RGBDirect
  157. if format == imgformat.macrgb:
  158. self.pixelSize = 32
  159. self.cmpSize = 8
  160. else:
  161. self.pixelSize = 16
  162. self.cmpSize = 5
  163. self.rowBytes = width*self.pixelSize/8
  164. def tostring(self, format=imgformat.macrgb):
  165. """Return raw data as a string in the specified format."""
  166. # is the native format requested? if so, just return data
  167. if (format == imgformat.macrgb and self.pixelSize == 32) or \
  168. (format == imgformat.macrgb16 and self.pixelsize == 16):
  169. return self.data
  170. # otherwise, convert to the requested format
  171. # (LATER!)
  172. raise "NotImplementedError", "data format conversion"
  173. def fromImage(self,im):
  174. """Initialize this PixMap from a PIL Image object."""
  175. # We need data in ARGB format; PIL can't currently do that,
  176. # but it can do RGBA, which we can use by inserting one null
  177. # up frontpm =
  178. if im.mode != 'RGBA': im = im.convert('RGBA')
  179. data = chr(0) + im.tostring()
  180. self.fromstring(data, im.size[0], im.size[1])
  181. def toImage(self):
  182. """Return the contents of this PixMap as a PIL Image object."""
  183. import Image
  184. # our tostring() method returns data in ARGB format,
  185. # whereas Image uses RGBA; a bit of slicing fixes this...
  186. data = self.tostring()[1:] + chr(0)
  187. bounds = self.bounds
  188. return Image.fromstring('RGBA',(bounds[2]-bounds[0],bounds[3]-bounds[1]),data)
  189. def test():
  190. import MacOS
  191. import EasyDialogs
  192. import Image
  193. path = EasyDialogs.AskFileForOpen("Image File:")
  194. if not path: return
  195. pm = PixMapWrapper()
  196. pm.fromImage( Image.open(path) )
  197. pm.blit(20,20)
  198. return pm