PcxImagePlugin.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. #
  2. # The Python Imaging Library.
  3. # $Id$
  4. #
  5. # PCX file handling
  6. #
  7. # This format was originally used by ZSoft's popular PaintBrush
  8. # program for the IBM PC. It is also supported by many MS-DOS and
  9. # Windows applications, including the Windows PaintBrush program in
  10. # Windows 3.
  11. #
  12. # history:
  13. # 1995-09-01 fl Created
  14. # 1996-05-20 fl Fixed RGB support
  15. # 1997-01-03 fl Fixed 2-bit and 4-bit support
  16. # 1999-02-03 fl Fixed 8-bit support (broken in 1.0b1)
  17. # 1999-02-07 fl Added write support
  18. # 2002-06-09 fl Made 2-bit and 4-bit support a bit more robust
  19. # 2002-07-30 fl Seek from to current position, not beginning of file
  20. # 2003-06-03 fl Extract DPI settings (info["dpi"])
  21. #
  22. # Copyright (c) 1997-2003 by Secret Labs AB.
  23. # Copyright (c) 1995-2003 by Fredrik Lundh.
  24. #
  25. # See the README file for information on usage and redistribution.
  26. #
  27. from __future__ import annotations
  28. __lazy_modules__ = {"PIL._binary", "io"}
  29. import io
  30. import logging
  31. from . import Image, ImageFile, ImagePalette
  32. from ._binary import i16le as i16
  33. from ._binary import o8
  34. from ._binary import o16le as o16
  35. TYPE_CHECKING = False
  36. if TYPE_CHECKING:
  37. from typing import IO
  38. logger = logging.getLogger(__name__)
  39. def _accept(prefix: bytes) -> bool:
  40. return len(prefix) >= 2 and prefix[0] == 10 and prefix[1] in [0, 2, 3, 5]
  41. ##
  42. # Image plugin for Paintbrush images.
  43. class PcxImageFile(ImageFile.ImageFile):
  44. format = "PCX"
  45. format_description = "Paintbrush"
  46. def _open(self) -> None:
  47. # header
  48. assert self.fp is not None
  49. s = self.fp.read(68)
  50. if not _accept(s):
  51. msg = "not a PCX file"
  52. raise SyntaxError(msg)
  53. # image
  54. bbox = i16(s, 4), i16(s, 6), i16(s, 8) + 1, i16(s, 10) + 1
  55. if bbox[2] <= bbox[0] or bbox[3] <= bbox[1]:
  56. msg = "bad PCX image size"
  57. raise SyntaxError(msg)
  58. logger.debug("BBox: %s %s %s %s", *bbox)
  59. offset = self.fp.tell() + 60
  60. # format
  61. version = s[1]
  62. bits = s[3]
  63. planes = s[65]
  64. provided_stride = i16(s, 66)
  65. logger.debug(
  66. "PCX version %s, bits %s, planes %s, stride %s",
  67. version,
  68. bits,
  69. planes,
  70. provided_stride,
  71. )
  72. self.info["dpi"] = i16(s, 12), i16(s, 14)
  73. if bits == 1 and planes == 1:
  74. mode = rawmode = "1"
  75. elif bits == 1 and planes in (2, 4):
  76. mode = "P"
  77. rawmode = f"P;{planes}L"
  78. self.palette = ImagePalette.raw("RGB", s[16:64])
  79. elif version == 5 and bits == 8 and planes == 1:
  80. mode = rawmode = "L"
  81. # FIXME: hey, this doesn't work with the incremental loader !!!
  82. self.fp.seek(-769, io.SEEK_END)
  83. s = self.fp.read(769)
  84. if len(s) == 769 and s[0] == 12:
  85. # check if the palette is linear grayscale
  86. for i in range(256):
  87. if s[i * 3 + 1 : i * 3 + 4] != o8(i) * 3:
  88. mode = rawmode = "P"
  89. break
  90. if mode == "P":
  91. self.palette = ImagePalette.raw("RGB", s[1:])
  92. elif version == 5 and bits == 8 and planes == 3:
  93. mode = "RGB"
  94. rawmode = "RGB;L"
  95. else:
  96. msg = "unknown PCX mode"
  97. raise OSError(msg)
  98. self._mode = mode
  99. self._size = bbox[2] - bbox[0], bbox[3] - bbox[1]
  100. # Don't trust the passed in stride.
  101. # Calculate the approximate position for ourselves.
  102. # CVE-2020-35653
  103. stride = (self._size[0] * bits + 7) // 8
  104. # While the specification states that this must be even,
  105. # not all images follow this
  106. if provided_stride != stride:
  107. stride += stride % 2
  108. bbox = (0, 0, *self.size)
  109. logger.debug("size: %sx%s", *self.size)
  110. self.tile = [ImageFile._Tile("pcx", bbox, offset, (rawmode, planes * stride))]
  111. # --------------------------------------------------------------------
  112. # save PCX files
  113. SAVE = {
  114. # mode: (version, bits, planes, raw mode)
  115. "1": (2, 1, 1, "1"),
  116. "L": (5, 8, 1, "L"),
  117. "P": (5, 8, 1, "P"),
  118. "RGB": (5, 8, 3, "RGB;L"),
  119. }
  120. def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
  121. if im.width == 0 or im.height == 0:
  122. msg = "Cannot write empty image as PCX"
  123. raise ValueError(msg)
  124. try:
  125. version, bits, planes, rawmode = SAVE[im.mode]
  126. except KeyError as e:
  127. msg = f"Cannot save {im.mode} images as PCX"
  128. raise ValueError(msg) from e
  129. # bytes per plane
  130. stride = (im.size[0] * bits + 7) // 8
  131. # stride should be even
  132. stride += stride % 2
  133. # Stride needs to be kept in sync with the PcxEncode.c version.
  134. # Ideally it should be passed in in the state, but the bytes value
  135. # gets overwritten.
  136. logger.debug(
  137. "PcxImagePlugin._save: xwidth: %d, bits: %d, stride: %d",
  138. im.size[0],
  139. bits,
  140. stride,
  141. )
  142. # under windows, we could determine the current screen size with
  143. # "Image.core.display_mode()[1]", but I think that's overkill...
  144. screen = im.size
  145. dpi = 100, 100
  146. # PCX header
  147. fp.write(
  148. o8(10)
  149. + o8(version)
  150. + o8(1)
  151. + o8(bits)
  152. + o16(0)
  153. + o16(0)
  154. + o16(im.size[0] - 1)
  155. + o16(im.size[1] - 1)
  156. + o16(dpi[0])
  157. + o16(dpi[1])
  158. + b"\0" * 24
  159. + b"\xff" * 24
  160. + b"\0"
  161. + o8(planes)
  162. + o16(stride)
  163. + o16(1)
  164. + o16(screen[0])
  165. + o16(screen[1])
  166. + b"\0" * 54
  167. )
  168. assert fp.tell() == 128
  169. ImageFile._save(
  170. im, fp, [ImageFile._Tile("pcx", (0, 0, *im.size), 0, (rawmode, bits * planes))]
  171. )
  172. if im.mode == "P":
  173. # colour palette
  174. fp.write(o8(12))
  175. palette = im.im.getpalette("RGB")
  176. palette += b"\x00" * (768 - len(palette))
  177. fp.write(palette) # 768 bytes
  178. elif im.mode == "L":
  179. # grayscale palette
  180. fp.write(o8(12))
  181. for i in range(256):
  182. fp.write(o8(i) * 3)
  183. # --------------------------------------------------------------------
  184. # registry
  185. Image.register_open(PcxImageFile.format, PcxImageFile, _accept)
  186. Image.register_save(PcxImageFile.format, _save)
  187. Image.register_extension(PcxImageFile.format, ".pcx")
  188. Image.register_mime(PcxImageFile.format, "image/x-pcx")