PyAccess.py 9.7 KB

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