PyAccess.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. #
  2. # The Python Imaging Library
  3. # Pillow fork
  4. #
  5. # Python implementation of the PixelAccess Object
  6. #
  7. # Copyright (c) 1997-2009 by Secret Labs AB. All rights reserved.
  8. # Copyright (c) 1995-2009 by Fredrik Lundh.
  9. # Copyright (c) 2013 Eric Soroos
  10. #
  11. # See the README file for information on usage and redistribution
  12. #
  13. # Notes:
  14. #
  15. # * Implements the pixel access object following Access.
  16. # * Does not implement the line functions, as they don't appear to be used
  17. # * Taking only the tuple form, which is used from python.
  18. # * Fill.c uses the integer form, but it's still going to use the old
  19. # Access.c implementation.
  20. #
  21. import logging
  22. import sys
  23. from cffi import FFI
  24. logger = logging.getLogger(__name__)
  25. defs = """
  26. struct Pixel_RGBA {
  27. unsigned char r,g,b,a;
  28. };
  29. struct Pixel_I16 {
  30. unsigned char l,r;
  31. };
  32. """
  33. ffi = FFI()
  34. ffi.cdef(defs)
  35. class PyAccess(object):
  36. def __init__(self, img, readonly=False):
  37. vals = dict(img.im.unsafe_ptrs)
  38. self.readonly = readonly
  39. self.image8 = ffi.cast("unsigned char **", vals["image8"])
  40. self.image32 = ffi.cast("int **", vals["image32"])
  41. self.image = ffi.cast("unsigned char **", vals["image"])
  42. self.xsize, self.ysize = img.im.size
  43. # Keep pointer to im object to prevent dereferencing.
  44. self._im = img.im
  45. if self._im.mode == "P":
  46. self._palette = img.palette
  47. # Debugging is polluting test traces, only useful here
  48. # when hacking on PyAccess
  49. # logger.debug("%s", vals)
  50. self._post_init()
  51. def _post_init(self):
  52. pass
  53. def __setitem__(self, xy, color):
  54. """
  55. Modifies the pixel at x,y. The color is given as a single
  56. numerical value for single band images, and a tuple for
  57. multi-band images
  58. :param xy: The pixel coordinate, given as (x, y). See
  59. :ref:`coordinate-system`.
  60. :param color: The pixel value.
  61. """
  62. if self.readonly:
  63. raise ValueError("Attempt to putpixel a read only image")
  64. (x, y) = xy
  65. if x < 0:
  66. x = self.xsize + x
  67. if y < 0:
  68. y = self.ysize + y
  69. (x, y) = self.check_xy((x, y))
  70. if (
  71. self._im.mode == "P"
  72. and isinstance(color, (list, tuple))
  73. and len(color) in [3, 4]
  74. ):
  75. # RGB or RGBA value for a P image
  76. color = self._palette.getcolor(color)
  77. return self.set_pixel(x, y, color)
  78. def __getitem__(self, xy):
  79. """
  80. Returns the pixel at x,y. The pixel is returned as a single
  81. value for single band images or a tuple for multiple band
  82. images
  83. :param xy: The pixel coordinate, given as (x, y). See
  84. :ref:`coordinate-system`.
  85. :returns: a pixel value for single band images, a tuple of
  86. pixel values for multiband images.
  87. """
  88. (x, y) = xy
  89. if x < 0:
  90. x = self.xsize + x
  91. if y < 0:
  92. y = self.ysize + y
  93. (x, y) = self.check_xy((x, y))
  94. return self.get_pixel(x, y)
  95. putpixel = __setitem__
  96. getpixel = __getitem__
  97. def check_xy(self, xy):
  98. (x, y) = xy
  99. if not (0 <= x < self.xsize and 0 <= y < self.ysize):
  100. raise ValueError("pixel location out of range")
  101. return xy
  102. class _PyAccess32_2(PyAccess):
  103. """ PA, LA, stored in first and last bytes of a 32 bit word """
  104. def _post_init(self, *args, **kwargs):
  105. self.pixels = ffi.cast("struct Pixel_RGBA **", self.image32)
  106. def get_pixel(self, x, y):
  107. pixel = self.pixels[y][x]
  108. return (pixel.r, pixel.a)
  109. def set_pixel(self, x, y, color):
  110. pixel = self.pixels[y][x]
  111. # tuple
  112. pixel.r = min(color[0], 255)
  113. pixel.a = min(color[1], 255)
  114. class _PyAccess32_3(PyAccess):
  115. """ RGB and friends, stored in the first three bytes of a 32 bit word """
  116. def _post_init(self, *args, **kwargs):
  117. self.pixels = ffi.cast("struct Pixel_RGBA **", self.image32)
  118. def get_pixel(self, x, y):
  119. pixel = self.pixels[y][x]
  120. return (pixel.r, pixel.g, pixel.b)
  121. def set_pixel(self, x, y, color):
  122. pixel = self.pixels[y][x]
  123. # tuple
  124. pixel.r = min(color[0], 255)
  125. pixel.g = min(color[1], 255)
  126. pixel.b = min(color[2], 255)
  127. pixel.a = 255
  128. class _PyAccess32_4(PyAccess):
  129. """ RGBA etc, all 4 bytes of a 32 bit word """
  130. def _post_init(self, *args, **kwargs):
  131. self.pixels = ffi.cast("struct Pixel_RGBA **", self.image32)
  132. def get_pixel(self, x, y):
  133. pixel = self.pixels[y][x]
  134. return (pixel.r, pixel.g, pixel.b, pixel.a)
  135. def set_pixel(self, x, y, color):
  136. pixel = self.pixels[y][x]
  137. # tuple
  138. pixel.r = min(color[0], 255)
  139. pixel.g = min(color[1], 255)
  140. pixel.b = min(color[2], 255)
  141. pixel.a = min(color[3], 255)
  142. class _PyAccess8(PyAccess):
  143. """ 1, L, P, 8 bit images stored as uint8 """
  144. def _post_init(self, *args, **kwargs):
  145. self.pixels = self.image8
  146. def get_pixel(self, x, y):
  147. return self.pixels[y][x]
  148. def set_pixel(self, x, y, color):
  149. try:
  150. # integer
  151. self.pixels[y][x] = min(color, 255)
  152. except TypeError:
  153. # tuple
  154. self.pixels[y][x] = min(color[0], 255)
  155. class _PyAccessI16_N(PyAccess):
  156. """ I;16 access, native bitendian without conversion """
  157. def _post_init(self, *args, **kwargs):
  158. self.pixels = ffi.cast("unsigned short **", self.image)
  159. def get_pixel(self, x, y):
  160. return self.pixels[y][x]
  161. def set_pixel(self, x, y, color):
  162. try:
  163. # integer
  164. self.pixels[y][x] = min(color, 65535)
  165. except TypeError:
  166. # tuple
  167. self.pixels[y][x] = min(color[0], 65535)
  168. class _PyAccessI16_L(PyAccess):
  169. """ I;16L access, with conversion """
  170. def _post_init(self, *args, **kwargs):
  171. self.pixels = ffi.cast("struct Pixel_I16 **", self.image)
  172. def get_pixel(self, x, y):
  173. pixel = self.pixels[y][x]
  174. return pixel.l + pixel.r * 256
  175. def set_pixel(self, x, y, color):
  176. pixel = self.pixels[y][x]
  177. try:
  178. color = min(color, 65535)
  179. except TypeError:
  180. color = min(color[0], 65535)
  181. pixel.l = color & 0xFF # noqa: E741
  182. pixel.r = color >> 8
  183. class _PyAccessI16_B(PyAccess):
  184. """ I;16B access, with conversion """
  185. def _post_init(self, *args, **kwargs):
  186. self.pixels = ffi.cast("struct Pixel_I16 **", self.image)
  187. def get_pixel(self, x, y):
  188. pixel = self.pixels[y][x]
  189. return pixel.l * 256 + pixel.r
  190. def set_pixel(self, x, y, color):
  191. pixel = self.pixels[y][x]
  192. try:
  193. color = min(color, 65535)
  194. except Exception:
  195. color = min(color[0], 65535)
  196. pixel.l = color >> 8 # noqa: E741
  197. pixel.r = color & 0xFF
  198. class _PyAccessI32_N(PyAccess):
  199. """ Signed Int32 access, native endian """
  200. def _post_init(self, *args, **kwargs):
  201. self.pixels = self.image32
  202. def get_pixel(self, x, y):
  203. return self.pixels[y][x]
  204. def set_pixel(self, x, y, color):
  205. self.pixels[y][x] = color
  206. class _PyAccessI32_Swap(PyAccess):
  207. """ I;32L/B access, with byteswapping conversion """
  208. def _post_init(self, *args, **kwargs):
  209. self.pixels = self.image32
  210. def reverse(self, i):
  211. orig = ffi.new("int *", i)
  212. chars = ffi.cast("unsigned char *", orig)
  213. chars[0], chars[1], chars[2], chars[3] = chars[3], chars[2], chars[1], chars[0]
  214. return ffi.cast("int *", chars)[0]
  215. def get_pixel(self, x, y):
  216. return self.reverse(self.pixels[y][x])
  217. def set_pixel(self, x, y, color):
  218. self.pixels[y][x] = self.reverse(color)
  219. class _PyAccessF(PyAccess):
  220. """ 32 bit float access """
  221. def _post_init(self, *args, **kwargs):
  222. self.pixels = ffi.cast("float **", self.image32)
  223. def get_pixel(self, x, y):
  224. return self.pixels[y][x]
  225. def set_pixel(self, x, y, color):
  226. try:
  227. # not a tuple
  228. self.pixels[y][x] = color
  229. except TypeError:
  230. # tuple
  231. self.pixels[y][x] = color[0]
  232. mode_map = {
  233. "1": _PyAccess8,
  234. "L": _PyAccess8,
  235. "P": _PyAccess8,
  236. "LA": _PyAccess32_2,
  237. "La": _PyAccess32_2,
  238. "PA": _PyAccess32_2,
  239. "RGB": _PyAccess32_3,
  240. "LAB": _PyAccess32_3,
  241. "HSV": _PyAccess32_3,
  242. "YCbCr": _PyAccess32_3,
  243. "RGBA": _PyAccess32_4,
  244. "RGBa": _PyAccess32_4,
  245. "RGBX": _PyAccess32_4,
  246. "CMYK": _PyAccess32_4,
  247. "F": _PyAccessF,
  248. "I": _PyAccessI32_N,
  249. }
  250. if sys.byteorder == "little":
  251. mode_map["I;16"] = _PyAccessI16_N
  252. mode_map["I;16L"] = _PyAccessI16_N
  253. mode_map["I;16B"] = _PyAccessI16_B
  254. mode_map["I;32L"] = _PyAccessI32_N
  255. mode_map["I;32B"] = _PyAccessI32_Swap
  256. else:
  257. mode_map["I;16"] = _PyAccessI16_L
  258. mode_map["I;16L"] = _PyAccessI16_L
  259. mode_map["I;16B"] = _PyAccessI16_N
  260. mode_map["I;32L"] = _PyAccessI32_Swap
  261. mode_map["I;32B"] = _PyAccessI32_N
  262. def new(img, readonly=False):
  263. access_type = mode_map.get(img.mode, None)
  264. if not access_type:
  265. logger.debug("PyAccess Not Implemented: %s", img.mode)
  266. return None
  267. return access_type(img, readonly)