PyAccess.py 9.4 KB

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