PcxImagePlugin.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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. import io
  29. import logging
  30. from typing import IO
  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. logger = logging.getLogger(__name__)
  36. def _accept(prefix: bytes) -> bool:
  37. return prefix[0] == 10 and prefix[1] in [0, 2, 3, 5]
  38. ##
  39. # Image plugin for Paintbrush images.
  40. class PcxImageFile(ImageFile.ImageFile):
  41. format = "PCX"
  42. format_description = "Paintbrush"
  43. def _open(self) -> None:
  44. # header
  45. assert self.fp is not None
  46. s = self.fp.read(128)
  47. if not _accept(s):
  48. msg = "not a PCX file"
  49. raise SyntaxError(msg)
  50. # image
  51. bbox = i16(s, 4), i16(s, 6), i16(s, 8) + 1, i16(s, 10) + 1
  52. if bbox[2] <= bbox[0] or bbox[3] <= bbox[1]:
  53. msg = "bad PCX image size"
  54. raise SyntaxError(msg)
  55. logger.debug("BBox: %s %s %s %s", *bbox)
  56. # format
  57. version = s[1]
  58. bits = s[3]
  59. planes = s[65]
  60. provided_stride = i16(s, 66)
  61. logger.debug(
  62. "PCX version %s, bits %s, planes %s, stride %s",
  63. version,
  64. bits,
  65. planes,
  66. provided_stride,
  67. )
  68. self.info["dpi"] = i16(s, 12), i16(s, 14)
  69. if bits == 1 and planes == 1:
  70. mode = rawmode = "1"
  71. elif bits == 1 and planes in (2, 4):
  72. mode = "P"
  73. rawmode = f"P;{planes}L"
  74. self.palette = ImagePalette.raw("RGB", s[16:64])
  75. elif version == 5 and bits == 8 and planes == 1:
  76. mode = rawmode = "L"
  77. # FIXME: hey, this doesn't work with the incremental loader !!!
  78. self.fp.seek(-769, io.SEEK_END)
  79. s = self.fp.read(769)
  80. if len(s) == 769 and s[0] == 12:
  81. # check if the palette is linear grayscale
  82. for i in range(256):
  83. if s[i * 3 + 1 : i * 3 + 4] != o8(i) * 3:
  84. mode = rawmode = "P"
  85. break
  86. if mode == "P":
  87. self.palette = ImagePalette.raw("RGB", s[1:])
  88. self.fp.seek(128)
  89. elif version == 5 and bits == 8 and planes == 3:
  90. mode = "RGB"
  91. rawmode = "RGB;L"
  92. else:
  93. msg = "unknown PCX mode"
  94. raise OSError(msg)
  95. self._mode = mode
  96. self._size = bbox[2] - bbox[0], bbox[3] - bbox[1]
  97. # Don't trust the passed in stride.
  98. # Calculate the approximate position for ourselves.
  99. # CVE-2020-35653
  100. stride = (self._size[0] * bits + 7) // 8
  101. # While the specification states that this must be even,
  102. # not all images follow this
  103. if provided_stride != stride:
  104. stride += stride % 2
  105. bbox = (0, 0) + self.size
  106. logger.debug("size: %sx%s", *self.size)
  107. self.tile = [
  108. ImageFile._Tile("pcx", bbox, self.fp.tell(), (rawmode, planes * stride))
  109. ]
  110. # --------------------------------------------------------------------
  111. # save PCX files
  112. SAVE = {
  113. # mode: (version, bits, planes, raw mode)
  114. "1": (2, 1, 1, "1"),
  115. "L": (5, 8, 1, "L"),
  116. "P": (5, 8, 1, "P"),
  117. "RGB": (5, 8, 3, "RGB;L"),
  118. }
  119. def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
  120. try:
  121. version, bits, planes, rawmode = SAVE[im.mode]
  122. except KeyError as e:
  123. msg = f"Cannot save {im.mode} images as PCX"
  124. raise ValueError(msg) from e
  125. # bytes per plane
  126. stride = (im.size[0] * bits + 7) // 8
  127. # stride should be even
  128. stride += stride % 2
  129. # Stride needs to be kept in sync with the PcxEncode.c version.
  130. # Ideally it should be passed in in the state, but the bytes value
  131. # gets overwritten.
  132. logger.debug(
  133. "PcxImagePlugin._save: xwidth: %d, bits: %d, stride: %d",
  134. im.size[0],
  135. bits,
  136. stride,
  137. )
  138. # under windows, we could determine the current screen size with
  139. # "Image.core.display_mode()[1]", but I think that's overkill...
  140. screen = im.size
  141. dpi = 100, 100
  142. # PCX header
  143. fp.write(
  144. o8(10)
  145. + o8(version)
  146. + o8(1)
  147. + o8(bits)
  148. + o16(0)
  149. + o16(0)
  150. + o16(im.size[0] - 1)
  151. + o16(im.size[1] - 1)
  152. + o16(dpi[0])
  153. + o16(dpi[1])
  154. + b"\0" * 24
  155. + b"\xFF" * 24
  156. + b"\0"
  157. + o8(planes)
  158. + o16(stride)
  159. + o16(1)
  160. + o16(screen[0])
  161. + o16(screen[1])
  162. + b"\0" * 54
  163. )
  164. assert fp.tell() == 128
  165. ImageFile._save(
  166. im, fp, [ImageFile._Tile("pcx", (0, 0) + im.size, 0, (rawmode, bits * planes))]
  167. )
  168. if im.mode == "P":
  169. # colour palette
  170. fp.write(o8(12))
  171. palette = im.im.getpalette("RGB", "RGB")
  172. palette += b"\x00" * (768 - len(palette))
  173. fp.write(palette) # 768 bytes
  174. elif im.mode == "L":
  175. # grayscale palette
  176. fp.write(o8(12))
  177. for i in range(256):
  178. fp.write(o8(i) * 3)
  179. # --------------------------------------------------------------------
  180. # registry
  181. Image.register_open(PcxImageFile.format, PcxImageFile, _accept)
  182. Image.register_save(PcxImageFile.format, _save)
  183. Image.register_extension(PcxImageFile.format, ".pcx")
  184. Image.register_mime(PcxImageFile.format, "image/x-pcx")