PyAccess.py 9.7 KB

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