MspImagePlugin.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. #
  2. # The Python Imaging Library.
  3. #
  4. # MSP file handling
  5. #
  6. # This is the format used by the Paint program in Windows 1 and 2.
  7. #
  8. # History:
  9. # 95-09-05 fl Created
  10. # 97-01-03 fl Read/write MSP images
  11. # 17-02-21 es Fixed RLE interpretation
  12. #
  13. # Copyright (c) Secret Labs AB 1997.
  14. # Copyright (c) Fredrik Lundh 1995-97.
  15. # Copyright (c) Eric Soroos 2017.
  16. #
  17. # See the README file for information on usage and redistribution.
  18. #
  19. # More info on this format: https://archive.org/details/gg243631
  20. # Page 313:
  21. # Figure 205. Windows Paint Version 1: "DanM" Format
  22. # Figure 206. Windows Paint Version 2: "LinS" Format. Used in Windows V2.03
  23. #
  24. # See also: https://www.fileformat.info/format/mspaint/egff.htm
  25. from __future__ import annotations
  26. __lazy_modules__ = {"PIL._binary", "struct"}
  27. import struct
  28. from . import Image, ImageFile
  29. from ._binary import i16le as i16
  30. from ._binary import o16le as o16
  31. TYPE_CHECKING = False
  32. if TYPE_CHECKING:
  33. from typing import IO
  34. #
  35. # read MSP files
  36. def _accept(prefix: bytes) -> bool:
  37. return prefix.startswith((b"DanM", b"LinS"))
  38. ##
  39. # Image plugin for Windows MSP images. This plugin supports both
  40. # uncompressed (Windows 1.0).
  41. class MspImageFile(ImageFile.ImageFile):
  42. format = "MSP"
  43. format_description = "Windows Paint"
  44. def _open(self) -> None:
  45. # Header
  46. assert self.fp is not None
  47. s = self.fp.read(32)
  48. if not _accept(s):
  49. msg = "not an MSP file"
  50. raise SyntaxError(msg)
  51. # Header checksum
  52. checksum = 0
  53. for i in range(0, 32, 2):
  54. checksum = checksum ^ i16(s, i)
  55. if checksum != 0:
  56. msg = "bad MSP checksum"
  57. raise SyntaxError(msg)
  58. self._mode = "1"
  59. self._size = i16(s, 4), i16(s, 6)
  60. if s.startswith(b"DanM"):
  61. self.tile = [ImageFile._Tile("raw", (0, 0, *self.size), 32, "1")]
  62. else:
  63. self.tile = [ImageFile._Tile("MSP", (0, 0, *self.size), 32)]
  64. class MspDecoder(ImageFile.PyDecoder):
  65. # The algo for the MSP decoder is from
  66. # https://www.fileformat.info/format/mspaint/egff.htm
  67. # cc-by-attribution -- That page references is taken from the
  68. # Encyclopedia of Graphics File Formats and is licensed by
  69. # O'Reilly under the Creative Common/Attribution license
  70. #
  71. # For RLE encoded files, the 32byte header is followed by a scan
  72. # line map, encoded as one 16bit word of encoded byte length per
  73. # line.
  74. #
  75. # NOTE: the encoded length of the line can be 0. This was not
  76. # handled in the previous version of this encoder, and there's no
  77. # mention of how to handle it in the documentation. From the few
  78. # examples I've seen, I've assumed that it is a fill of the
  79. # background color, in this case, white.
  80. #
  81. #
  82. # Pseudocode of the decoder:
  83. # Read a BYTE value as the RunType
  84. # If the RunType value is zero
  85. # Read next byte as the RunCount
  86. # Read the next byte as the RunValue
  87. # Write the RunValue byte RunCount times
  88. # If the RunType value is non-zero
  89. # Use this value as the RunCount
  90. # Read and write the next RunCount bytes literally
  91. #
  92. # e.g.:
  93. # 0x00 03 ff 05 00 01 02 03 04
  94. # would yield the bytes:
  95. # 0xff ff ff 00 01 02 03 04
  96. #
  97. # which are then interpreted as a bit packed mode '1' image
  98. _pulls_fd = True
  99. def decode(self, buffer: Image.DecoderInput) -> tuple[int, int]:
  100. assert self.fd is not None
  101. data = bytearray()
  102. blank_line = bytearray((0xFF,) * ((self.state.xsize + 7) // 8))
  103. try:
  104. self.fd.seek(32)
  105. rowmap = struct.unpack_from(
  106. f"<{self.state.ysize}H", self.fd.read(self.state.ysize * 2)
  107. )
  108. except struct.error as e:
  109. msg = "Truncated MSP file in row map"
  110. raise OSError(msg) from e
  111. for y, rowlen in enumerate(rowmap):
  112. try:
  113. if rowlen == 0:
  114. data += blank_line
  115. continue
  116. row = self.fd.read(rowlen)
  117. if len(row) != rowlen:
  118. msg = f"Truncated MSP file, expected {rowlen} bytes on row {y}"
  119. raise OSError(msg)
  120. idx = 0
  121. row_data = bytearray()
  122. while idx < rowlen:
  123. runtype = row[idx]
  124. idx += 1
  125. if runtype == 0:
  126. runcount, runval = struct.unpack_from("Bc", row, idx)
  127. runcount = min(runcount, self.state.xsize - len(row_data))
  128. row_data += runval * runcount
  129. idx += 2
  130. else:
  131. runcount = min(runtype, self.state.xsize - len(row_data))
  132. row_data += row[idx : idx + runcount]
  133. idx += runcount
  134. data += row_data
  135. except struct.error as e:
  136. msg = f"Corrupted MSP file in row {y}"
  137. raise OSError(msg) from e
  138. self.set_as_raw(bytes(data), "1")
  139. return -1, 0
  140. Image.register_decoder("MSP", MspDecoder)
  141. #
  142. # write MSP files (uncompressed only)
  143. def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
  144. if im.mode != "1":
  145. msg = f"cannot write mode {im.mode} as MSP"
  146. raise OSError(msg)
  147. # create MSP header
  148. header = [0] * 16
  149. header[0], header[1] = i16(b"Da"), i16(b"nM") # version 1
  150. header[2], header[3] = im.size
  151. header[4], header[5] = 1, 1
  152. header[6], header[7] = 1, 1
  153. header[8], header[9] = im.size
  154. checksum = 0
  155. for h in header:
  156. checksum = checksum ^ h
  157. header[12] = checksum # FIXME: is this the right field?
  158. # header
  159. for h in header:
  160. fp.write(o16(h))
  161. # image body
  162. ImageFile._save(im, fp, [ImageFile._Tile("raw", (0, 0, *im.size), 32, "1")])
  163. #
  164. # registry
  165. Image.register_open(MspImageFile.format, MspImageFile, _accept)
  166. Image.register_save(MspImageFile.format, _save)
  167. Image.register_extension(MspImageFile.format, ".msp")