blob: a4bacaa6b778c2a0084eaf0b6a5261dff263d40a [file] [log] [blame]
Jack Jansen0d3be0a1999-04-13 11:45:46 +00001"""PixMapWrapper - defines the PixMapWrapper class, which wraps an opaque
Tim Peters182b5ac2004-07-18 06:16:08 +00002QuickDraw PixMap data structure in a handy Python class. Also provides
Jack Jansen0d3be0a1999-04-13 11:45:46 +00003methods to convert to/from pixel data (from, e.g., the img module) or a
4Python Imaging Library Image object.
5
6J. Strout <joe@strout.net> February 1999"""
7
Jack Jansen5a6fdcd2001-08-25 12:15:04 +00008from Carbon import Qd
9from Carbon import QuickDraw
Jack Jansen0d3be0a1999-04-13 11:45:46 +000010import struct
11import MacOS
12import img
13import imgformat
14
15# PixMap data structure element format (as used with struct)
16_pmElemFormat = {
Jack Jansen0ae32202003-04-09 13:25:43 +000017 'baseAddr':'l', # address of pixel data
18 'rowBytes':'H', # bytes per row, plus 0x8000
19 'bounds':'hhhh', # coordinates imposed over pixel data
20 'top':'h',
21 'left':'h',
22 'bottom':'h',
23 'right':'h',
24 'pmVersion':'h', # flags for Color QuickDraw
25 'packType':'h', # format of compression algorithm
26 'packSize':'l', # size after compression
27 'hRes':'l', # horizontal pixels per inch
28 'vRes':'l', # vertical pixels per inch
29 'pixelType':'h', # pixel format
30 'pixelSize':'h', # bits per pixel
31 'cmpCount':'h', # color components per pixel
32 'cmpSize':'h', # bits per component
33 'planeBytes':'l', # offset in bytes to next plane
34 'pmTable':'l', # handle to color table
35 'pmReserved':'l' # reserved for future use
Jack Jansen0d3be0a1999-04-13 11:45:46 +000036}
37
38# PixMap data structure element offset
39_pmElemOffset = {
Jack Jansen0ae32202003-04-09 13:25:43 +000040 'baseAddr':0,
41 'rowBytes':4,
42 'bounds':6,
43 'top':6,
44 'left':8,
45 'bottom':10,
46 'right':12,
47 'pmVersion':14,
48 'packType':16,
49 'packSize':18,
50 'hRes':22,
51 'vRes':26,
52 'pixelType':30,
53 'pixelSize':32,
54 'cmpCount':34,
55 'cmpSize':36,
56 'planeBytes':38,
57 'pmTable':42,
58 'pmReserved':46
Jack Jansen0d3be0a1999-04-13 11:45:46 +000059}
60
61class PixMapWrapper:
Jack Jansen0ae32202003-04-09 13:25:43 +000062 """PixMapWrapper -- wraps the QD PixMap object in a Python class,
63 with methods to easily get/set various pixmap fields. Note: Use the
64 PixMap() method when passing to QD calls."""
Jack Jansen0d3be0a1999-04-13 11:45:46 +000065
Jack Jansen0ae32202003-04-09 13:25:43 +000066 def __init__(self):
67 self.__dict__['data'] = ''
68 self._header = struct.pack("lhhhhhhhlllhhhhlll",
69 id(self.data)+MacOS.string_id_to_buffer,
70 0, # rowBytes
71 0, 0, 0, 0, # bounds
72 0, # pmVersion
73 0, 0, # packType, packSize
74 72<<16, 72<<16, # hRes, vRes
75 QuickDraw.RGBDirect, # pixelType
76 16, # pixelSize
77 2, 5, # cmpCount, cmpSize,
78 0, 0, 0) # planeBytes, pmTable, pmReserved
79 self.__dict__['_pm'] = Qd.RawBitMap(self._header)
Tim Peters182b5ac2004-07-18 06:16:08 +000080
Jack Jansen0ae32202003-04-09 13:25:43 +000081 def _stuff(self, element, bytes):
82 offset = _pmElemOffset[element]
83 fmt = _pmElemFormat[element]
84 self._header = self._header[:offset] \
85 + struct.pack(fmt, bytes) \
86 + self._header[offset + struct.calcsize(fmt):]
87 self.__dict__['_pm'] = None
Tim Peters182b5ac2004-07-18 06:16:08 +000088
Jack Jansen0ae32202003-04-09 13:25:43 +000089 def _unstuff(self, element):
90 offset = _pmElemOffset[element]
91 fmt = _pmElemFormat[element]
92 return struct.unpack(fmt, self._header[offset:offset+struct.calcsize(fmt)])[0]
Jack Jansen0d3be0a1999-04-13 11:45:46 +000093
Jack Jansen0ae32202003-04-09 13:25:43 +000094 def __setattr__(self, attr, val):
95 if attr == 'baseAddr':
Collin Winter6cd2a202007-08-30 18:11:48 +000096 raise RuntimeError("don't assign to .baseAddr "
97 "-- assign to .data instead")
Jack Jansen0ae32202003-04-09 13:25:43 +000098 elif attr == 'data':
99 self.__dict__['data'] = val
100 self._stuff('baseAddr', id(self.data) + MacOS.string_id_to_buffer)
101 elif attr == 'rowBytes':
102 # high bit is always set for some odd reason
103 self._stuff('rowBytes', val | 0x8000)
104 elif attr == 'bounds':
105 # assume val is in official Left, Top, Right, Bottom order!
106 self._stuff('left',val[0])
107 self._stuff('top',val[1])
108 self._stuff('right',val[2])
109 self._stuff('bottom',val[3])
110 elif attr == 'hRes' or attr == 'vRes':
111 # 16.16 fixed format, so just shift 16 bits
112 self._stuff(attr, int(val) << 16)
113 elif attr in _pmElemFormat.keys():
114 # any other pm attribute -- just stuff
115 self._stuff(attr, val)
116 else:
Tim Peters182b5ac2004-07-18 06:16:08 +0000117 self.__dict__[attr] = val
Jack Jansen0d3be0a1999-04-13 11:45:46 +0000118
Jack Jansen0ae32202003-04-09 13:25:43 +0000119 def __getattr__(self, attr):
120 if attr == 'rowBytes':
121 # high bit is always set for some odd reason
122 return self._unstuff('rowBytes') & 0x7FFF
123 elif attr == 'bounds':
124 # return bounds in official Left, Top, Right, Bottom order!
Collin Winter6cd2a202007-08-30 18:11:48 +0000125 return (
Jack Jansen0ae32202003-04-09 13:25:43 +0000126 self._unstuff('left'),
127 self._unstuff('top'),
128 self._unstuff('right'),
129 self._unstuff('bottom') )
130 elif attr == 'hRes' or attr == 'vRes':
131 # 16.16 fixed format, so just shift 16 bits
132 return self._unstuff(attr) >> 16
133 elif attr in _pmElemFormat.keys():
134 # any other pm attribute -- just unstuff
135 return self._unstuff(attr)
136 else:
Tim Peters182b5ac2004-07-18 06:16:08 +0000137 return self.__dict__[attr]
Jack Jansen0d3be0a1999-04-13 11:45:46 +0000138
Tim Peters182b5ac2004-07-18 06:16:08 +0000139
Jack Jansen0ae32202003-04-09 13:25:43 +0000140 def PixMap(self):
141 "Return a QuickDraw PixMap corresponding to this data."
142 if not self.__dict__['_pm']:
143 self.__dict__['_pm'] = Qd.RawBitMap(self._header)
144 return self.__dict__['_pm']
Jack Jansen0d3be0a1999-04-13 11:45:46 +0000145
Jack Jansen0ae32202003-04-09 13:25:43 +0000146 def blit(self, x1=0,y1=0,x2=None,y2=None, port=None):
Tim Peters182b5ac2004-07-18 06:16:08 +0000147 """Draw this pixmap into the given (default current) grafport."""
Jack Jansen0ae32202003-04-09 13:25:43 +0000148 src = self.bounds
149 dest = [x1,y1,x2,y2]
150 if x2 == None:
151 dest[2] = x1 + src[2]-src[0]
152 if y2 == None:
153 dest[3] = y1 + src[3]-src[1]
154 if not port: port = Qd.GetPort()
155 Qd.CopyBits(self.PixMap(), port.GetPortBitMapForCopyBits(), src, tuple(dest),
156 QuickDraw.srcCopy, None)
Tim Peters182b5ac2004-07-18 06:16:08 +0000157
Jack Jansen0ae32202003-04-09 13:25:43 +0000158 def fromstring(self,s,width,height,format=imgformat.macrgb):
159 """Stuff this pixmap with raw pixel data from a string.
160 Supply width, height, and one of the imgformat specifiers."""
161 # we only support 16- and 32-bit mac rgb...
162 # so convert if necessary
163 if format != imgformat.macrgb and format != imgformat.macrgb16:
164 # (LATER!)
Collin Winter6cd2a202007-08-30 18:11:48 +0000165 raise NotImplementedError("conversion to macrgb or macrgb16")
Jack Jansen0ae32202003-04-09 13:25:43 +0000166 self.data = s
167 self.bounds = (0,0,width,height)
168 self.cmpCount = 3
169 self.pixelType = QuickDraw.RGBDirect
170 if format == imgformat.macrgb:
171 self.pixelSize = 32
172 self.cmpSize = 8
173 else:
174 self.pixelSize = 16
175 self.cmpSize = 5
176 self.rowBytes = width*self.pixelSize/8
Jack Jansen0d3be0a1999-04-13 11:45:46 +0000177
Jack Jansen0ae32202003-04-09 13:25:43 +0000178 def tostring(self, format=imgformat.macrgb):
179 """Return raw data as a string in the specified format."""
180 # is the native format requested? if so, just return data
181 if (format == imgformat.macrgb and self.pixelSize == 32) or \
182 (format == imgformat.macrgb16 and self.pixelsize == 16):
183 return self.data
184 # otherwise, convert to the requested format
185 # (LATER!)
Collin Winter6cd2a202007-08-30 18:11:48 +0000186 raise NotImplementedError("data format conversion")
Jack Jansen0d3be0a1999-04-13 11:45:46 +0000187
Jack Jansen0ae32202003-04-09 13:25:43 +0000188 def fromImage(self,im):
189 """Initialize this PixMap from a PIL Image object."""
190 # We need data in ARGB format; PIL can't currently do that,
191 # but it can do RGBA, which we can use by inserting one null
Tim Peters182b5ac2004-07-18 06:16:08 +0000192 # up frontpm =
Jack Jansen0ae32202003-04-09 13:25:43 +0000193 if im.mode != 'RGBA': im = im.convert('RGBA')
194 data = chr(0) + im.tostring()
195 self.fromstring(data, im.size[0], im.size[1])
Jack Jansen0d3be0a1999-04-13 11:45:46 +0000196
Jack Jansen0ae32202003-04-09 13:25:43 +0000197 def toImage(self):
198 """Return the contents of this PixMap as a PIL Image object."""
199 import Image
200 # our tostring() method returns data in ARGB format,
201 # whereas Image uses RGBA; a bit of slicing fixes this...
202 data = self.tostring()[1:] + chr(0)
203 bounds = self.bounds
204 return Image.fromstring('RGBA',(bounds[2]-bounds[0],bounds[3]-bounds[1]),data)
Jack Jansen0d3be0a1999-04-13 11:45:46 +0000205
206def test():
Jack Jansen0ae32202003-04-09 13:25:43 +0000207 import MacOS
208 import EasyDialogs
209 import Image
210 path = EasyDialogs.AskFileForOpen("Image File:")
211 if not path: return
212 pm = PixMapWrapper()
213 pm.fromImage( Image.open(path) )
214 pm.blit(20,20)
215 return pm