PcxImagePlugin.py 5.9 KB

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