CurImagePlugin.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. #
  2. # The Python Imaging Library.
  3. # $Id$
  4. #
  5. # Windows Cursor support for PIL
  6. #
  7. # notes:
  8. # uses BmpImagePlugin.py to read the bitmap data.
  9. #
  10. # history:
  11. # 96-05-27 fl Created
  12. #
  13. # Copyright (c) Secret Labs AB 1997.
  14. # Copyright (c) Fredrik Lundh 1996.
  15. #
  16. # See the README file for information on usage and redistribution.
  17. #
  18. from __future__ import annotations
  19. __lazy_modules__ = {"PIL._binary"}
  20. from . import BmpImagePlugin, Image, ImageOps
  21. from ._binary import i16le as i16
  22. from ._binary import i32le as i32
  23. #
  24. # --------------------------------------------------------------------
  25. def _accept(prefix: bytes) -> bool:
  26. return prefix.startswith(b"\0\0\2\0")
  27. ##
  28. # Image plugin for Windows Cursor files.
  29. class CurImageFile(BmpImagePlugin.BmpImageFile):
  30. format = "CUR"
  31. format_description = "Windows Cursor"
  32. def _open(self) -> None:
  33. assert self.fp is not None
  34. offset = self.fp.tell()
  35. # check magic
  36. s = self.fp.read(6)
  37. if not _accept(s):
  38. msg = "not a CUR file"
  39. raise SyntaxError(msg)
  40. # pick the largest cursor in the file
  41. m = b""
  42. for i in range(i16(s, 4)):
  43. s = self.fp.read(16)
  44. if not m:
  45. m = s
  46. elif s[0] > m[0] and s[1] > m[1]:
  47. m = s
  48. if not m:
  49. msg = "No cursors were found"
  50. raise TypeError(msg)
  51. # load as bitmap
  52. self._bitmap(i32(m, 12) + offset)
  53. self._masked = self.mode in ("1", "L")
  54. if self._masked:
  55. self._rawmode = self.mode
  56. self._mode = "LA"
  57. # patch up the bitmap height
  58. self._size = self.width, self.height // 2
  59. if not self._masked:
  60. self.tile = [self.tile[0]._replace(extents=(0, 0, *self.size))]
  61. def load_prepare(self) -> None:
  62. if self._masked:
  63. self._mode = self._rawmode
  64. self._size = self.width, self.height * 2
  65. super().load_prepare()
  66. def load_end(self) -> None:
  67. if not self._masked:
  68. return
  69. self._mode = "LA"
  70. new_height = self.height // 2
  71. and_mask = self.im.crop((0, 0, self.width, new_height))
  72. xor_mask = self.im.crop((0, new_height, self.width, self.height))
  73. self._size = self.width, new_height
  74. self._im = Image.core.fill(self.mode, self.size)
  75. self._im.paste(
  76. xor_mask.convert(self.mode),
  77. (0, 0, *self.size),
  78. ImageOps.invert(Image.Image()._new(and_mask)).im,
  79. )
  80. #
  81. # --------------------------------------------------------------------
  82. Image.register_open(CurImageFile.format, CurImageFile, _accept)
  83. Image.register_extension(CurImageFile.format, ".cur")