Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

PpmImagePlugin.py 11KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. #
  2. # The Python Imaging Library.
  3. # $Id$
  4. #
  5. # PPM support for PIL
  6. #
  7. # History:
  8. # 96-03-24 fl Created
  9. # 98-03-06 fl Write RGBA images (as RGB, that is)
  10. #
  11. # Copyright (c) Secret Labs AB 1997-98.
  12. # Copyright (c) Fredrik Lundh 1996.
  13. #
  14. # See the README file for information on usage and redistribution.
  15. #
  16. from . import Image, ImageFile
  17. from ._binary import i16be as i16
  18. from ._binary import o8
  19. from ._binary import o32le as o32
  20. #
  21. # --------------------------------------------------------------------
  22. b_whitespace = b"\x20\x09\x0a\x0b\x0c\x0d"
  23. MODES = {
  24. # standard
  25. b"P1": "1",
  26. b"P2": "L",
  27. b"P3": "RGB",
  28. b"P4": "1",
  29. b"P5": "L",
  30. b"P6": "RGB",
  31. # extensions
  32. b"P0CMYK": "CMYK",
  33. # PIL extensions (for test purposes only)
  34. b"PyP": "P",
  35. b"PyRGBA": "RGBA",
  36. b"PyCMYK": "CMYK",
  37. }
  38. def _accept(prefix):
  39. return prefix[0:1] == b"P" and prefix[1] in b"0123456y"
  40. ##
  41. # Image plugin for PBM, PGM, and PPM images.
  42. class PpmImageFile(ImageFile.ImageFile):
  43. format = "PPM"
  44. format_description = "Pbmplus image"
  45. def _read_magic(self):
  46. magic = b""
  47. # read until whitespace or longest available magic number
  48. for _ in range(6):
  49. c = self.fp.read(1)
  50. if not c or c in b_whitespace:
  51. break
  52. magic += c
  53. return magic
  54. def _read_token(self):
  55. token = b""
  56. while len(token) <= 10: # read until next whitespace or limit of 10 characters
  57. c = self.fp.read(1)
  58. if not c:
  59. break
  60. elif c in b_whitespace: # token ended
  61. if not token:
  62. # skip whitespace at start
  63. continue
  64. break
  65. elif c == b"#":
  66. # ignores rest of the line; stops at CR, LF or EOF
  67. while self.fp.read(1) not in b"\r\n":
  68. pass
  69. continue
  70. token += c
  71. if not token:
  72. # Token was not even 1 byte
  73. msg = "Reached EOF while reading header"
  74. raise ValueError(msg)
  75. elif len(token) > 10:
  76. msg = f"Token too long in file header: {token.decode()}"
  77. raise ValueError(msg)
  78. return token
  79. def _open(self):
  80. magic_number = self._read_magic()
  81. try:
  82. mode = MODES[magic_number]
  83. except KeyError:
  84. msg = "not a PPM file"
  85. raise SyntaxError(msg)
  86. if magic_number in (b"P1", b"P4"):
  87. self.custom_mimetype = "image/x-portable-bitmap"
  88. elif magic_number in (b"P2", b"P5"):
  89. self.custom_mimetype = "image/x-portable-graymap"
  90. elif magic_number in (b"P3", b"P6"):
  91. self.custom_mimetype = "image/x-portable-pixmap"
  92. maxval = None
  93. decoder_name = "raw"
  94. if magic_number in (b"P1", b"P2", b"P3"):
  95. decoder_name = "ppm_plain"
  96. for ix in range(3):
  97. token = int(self._read_token())
  98. if ix == 0: # token is the x size
  99. xsize = token
  100. elif ix == 1: # token is the y size
  101. ysize = token
  102. if mode == "1":
  103. self.mode = "1"
  104. rawmode = "1;I"
  105. break
  106. else:
  107. self.mode = rawmode = mode
  108. elif ix == 2: # token is maxval
  109. maxval = token
  110. if not 0 < maxval < 65536:
  111. msg = "maxval must be greater than 0 and less than 65536"
  112. raise ValueError(msg)
  113. if maxval > 255 and mode == "L":
  114. self.mode = "I"
  115. if decoder_name != "ppm_plain":
  116. # If maxval matches a bit depth, use the raw decoder directly
  117. if maxval == 65535 and mode == "L":
  118. rawmode = "I;16B"
  119. elif maxval != 255:
  120. decoder_name = "ppm"
  121. args = (rawmode, 0, 1) if decoder_name == "raw" else (rawmode, maxval)
  122. self._size = xsize, ysize
  123. self.tile = [(decoder_name, (0, 0, xsize, ysize), self.fp.tell(), args)]
  124. #
  125. # --------------------------------------------------------------------
  126. class PpmPlainDecoder(ImageFile.PyDecoder):
  127. _pulls_fd = True
  128. def _read_block(self):
  129. return self.fd.read(ImageFile.SAFEBLOCK)
  130. def _find_comment_end(self, block, start=0):
  131. a = block.find(b"\n", start)
  132. b = block.find(b"\r", start)
  133. return min(a, b) if a * b > 0 else max(a, b) # lowest nonnegative index (or -1)
  134. def _ignore_comments(self, block):
  135. if self._comment_spans:
  136. # Finish current comment
  137. while block:
  138. comment_end = self._find_comment_end(block)
  139. if comment_end != -1:
  140. # Comment ends in this block
  141. # Delete tail of comment
  142. block = block[comment_end + 1 :]
  143. break
  144. else:
  145. # Comment spans whole block
  146. # So read the next block, looking for the end
  147. block = self._read_block()
  148. # Search for any further comments
  149. self._comment_spans = False
  150. while True:
  151. comment_start = block.find(b"#")
  152. if comment_start == -1:
  153. # No comment found
  154. break
  155. comment_end = self._find_comment_end(block, comment_start)
  156. if comment_end != -1:
  157. # Comment ends in this block
  158. # Delete comment
  159. block = block[:comment_start] + block[comment_end + 1 :]
  160. else:
  161. # Comment continues to next block(s)
  162. block = block[:comment_start]
  163. self._comment_spans = True
  164. break
  165. return block
  166. def _decode_bitonal(self):
  167. """
  168. This is a separate method because in the plain PBM format, all data tokens are
  169. exactly one byte, so the inter-token whitespace is optional.
  170. """
  171. data = bytearray()
  172. total_bytes = self.state.xsize * self.state.ysize
  173. while len(data) != total_bytes:
  174. block = self._read_block() # read next block
  175. if not block:
  176. # eof
  177. break
  178. block = self._ignore_comments(block)
  179. tokens = b"".join(block.split())
  180. for token in tokens:
  181. if token not in (48, 49):
  182. msg = b"Invalid token for this mode: %s" % bytes([token])
  183. raise ValueError(msg)
  184. data = (data + tokens)[:total_bytes]
  185. invert = bytes.maketrans(b"01", b"\xFF\x00")
  186. return data.translate(invert)
  187. def _decode_blocks(self, maxval):
  188. data = bytearray()
  189. max_len = 10
  190. out_byte_count = 4 if self.mode == "I" else 1
  191. out_max = 65535 if self.mode == "I" else 255
  192. bands = Image.getmodebands(self.mode)
  193. total_bytes = self.state.xsize * self.state.ysize * bands * out_byte_count
  194. half_token = False
  195. while len(data) != total_bytes:
  196. block = self._read_block() # read next block
  197. if not block:
  198. if half_token:
  199. block = bytearray(b" ") # flush half_token
  200. else:
  201. # eof
  202. break
  203. block = self._ignore_comments(block)
  204. if half_token:
  205. block = half_token + block # stitch half_token to new block
  206. half_token = False
  207. tokens = block.split()
  208. if block and not block[-1:].isspace(): # block might split token
  209. half_token = tokens.pop() # save half token for later
  210. if len(half_token) > max_len: # prevent buildup of half_token
  211. msg = (
  212. b"Token too long found in data: %s" % half_token[: max_len + 1]
  213. )
  214. raise ValueError(msg)
  215. for token in tokens:
  216. if len(token) > max_len:
  217. msg = b"Token too long found in data: %s" % token[: max_len + 1]
  218. raise ValueError(msg)
  219. value = int(token)
  220. if value > maxval:
  221. msg = f"Channel value too large for this mode: {value}"
  222. raise ValueError(msg)
  223. value = round(value / maxval * out_max)
  224. data += o32(value) if self.mode == "I" else o8(value)
  225. if len(data) == total_bytes: # finished!
  226. break
  227. return data
  228. def decode(self, buffer):
  229. self._comment_spans = False
  230. if self.mode == "1":
  231. data = self._decode_bitonal()
  232. rawmode = "1;8"
  233. else:
  234. maxval = self.args[-1]
  235. data = self._decode_blocks(maxval)
  236. rawmode = "I;32" if self.mode == "I" else self.mode
  237. self.set_as_raw(bytes(data), rawmode)
  238. return -1, 0
  239. class PpmDecoder(ImageFile.PyDecoder):
  240. _pulls_fd = True
  241. def decode(self, buffer):
  242. data = bytearray()
  243. maxval = self.args[-1]
  244. in_byte_count = 1 if maxval < 256 else 2
  245. out_byte_count = 4 if self.mode == "I" else 1
  246. out_max = 65535 if self.mode == "I" else 255
  247. bands = Image.getmodebands(self.mode)
  248. while len(data) < self.state.xsize * self.state.ysize * bands * out_byte_count:
  249. pixels = self.fd.read(in_byte_count * bands)
  250. if len(pixels) < in_byte_count * bands:
  251. # eof
  252. break
  253. for b in range(bands):
  254. value = (
  255. pixels[b] if in_byte_count == 1 else i16(pixels, b * in_byte_count)
  256. )
  257. value = min(out_max, round(value / maxval * out_max))
  258. data += o32(value) if self.mode == "I" else o8(value)
  259. rawmode = "I;32" if self.mode == "I" else self.mode
  260. self.set_as_raw(bytes(data), rawmode)
  261. return -1, 0
  262. #
  263. # --------------------------------------------------------------------
  264. def _save(im, fp, filename):
  265. if im.mode == "1":
  266. rawmode, head = "1;I", b"P4"
  267. elif im.mode == "L":
  268. rawmode, head = "L", b"P5"
  269. elif im.mode == "I":
  270. rawmode, head = "I;16B", b"P5"
  271. elif im.mode in ("RGB", "RGBA"):
  272. rawmode, head = "RGB", b"P6"
  273. else:
  274. msg = f"cannot write mode {im.mode} as PPM"
  275. raise OSError(msg)
  276. fp.write(head + b"\n%d %d\n" % im.size)
  277. if head == b"P6":
  278. fp.write(b"255\n")
  279. elif head == b"P5":
  280. if rawmode == "L":
  281. fp.write(b"255\n")
  282. else:
  283. fp.write(b"65535\n")
  284. ImageFile._save(im, fp, [("raw", (0, 0) + im.size, 0, (rawmode, 0, 1))])
  285. # ALTERNATIVE: save via builtin debug function
  286. # im._dump(filename)
  287. #
  288. # --------------------------------------------------------------------
  289. Image.register_open(PpmImageFile.format, PpmImageFile, _accept)
  290. Image.register_save(PpmImageFile.format, _save)
  291. Image.register_decoder("ppm", PpmDecoder)
  292. Image.register_decoder("ppm_plain", PpmPlainDecoder)
  293. Image.register_extensions(PpmImageFile.format, [".pbm", ".pgm", ".ppm", ".pnm"])
  294. Image.register_mime(PpmImageFile.format, "image/x-portable-anymap")