PpmImagePlugin.py 11 KB

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