ImImagePlugin.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. #
  2. # The Python Imaging Library.
  3. # $Id$
  4. #
  5. # IFUNC IM file handling for PIL
  6. #
  7. # history:
  8. # 1995-09-01 fl Created.
  9. # 1997-01-03 fl Save palette images
  10. # 1997-01-08 fl Added sequence support
  11. # 1997-01-23 fl Added P and RGB save support
  12. # 1997-05-31 fl Read floating point images
  13. # 1997-06-22 fl Save floating point images
  14. # 1997-08-27 fl Read and save 1-bit images
  15. # 1998-06-25 fl Added support for RGB+LUT images
  16. # 1998-07-02 fl Added support for YCC images
  17. # 1998-07-15 fl Renamed offset attribute to avoid name clash
  18. # 1998-12-29 fl Added I;16 support
  19. # 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.7)
  20. # 2003-09-26 fl Added LA/PA support
  21. #
  22. # Copyright (c) 1997-2003 by Secret Labs AB.
  23. # Copyright (c) 1995-2001 by Fredrik Lundh.
  24. #
  25. # See the README file for information on usage and redistribution.
  26. #
  27. from __future__ import annotations
  28. import os
  29. import re
  30. from typing import IO, Any
  31. from . import Image, ImageFile, ImagePalette
  32. # --------------------------------------------------------------------
  33. # Standard tags
  34. COMMENT = "Comment"
  35. DATE = "Date"
  36. EQUIPMENT = "Digitalization equipment"
  37. FRAMES = "File size (no of images)"
  38. LUT = "Lut"
  39. NAME = "Name"
  40. SCALE = "Scale (x,y)"
  41. SIZE = "Image size (x*y)"
  42. MODE = "Image type"
  43. TAGS = {
  44. COMMENT: 0,
  45. DATE: 0,
  46. EQUIPMENT: 0,
  47. FRAMES: 0,
  48. LUT: 0,
  49. NAME: 0,
  50. SCALE: 0,
  51. SIZE: 0,
  52. MODE: 0,
  53. }
  54. OPEN = {
  55. # ifunc93/p3cfunc formats
  56. "0 1 image": ("1", "1"),
  57. "L 1 image": ("1", "1"),
  58. "Greyscale image": ("L", "L"),
  59. "Grayscale image": ("L", "L"),
  60. "RGB image": ("RGB", "RGB;L"),
  61. "RLB image": ("RGB", "RLB"),
  62. "RYB image": ("RGB", "RLB"),
  63. "B1 image": ("1", "1"),
  64. "B2 image": ("P", "P;2"),
  65. "B4 image": ("P", "P;4"),
  66. "X 24 image": ("RGB", "RGB"),
  67. "L 32 S image": ("I", "I;32"),
  68. "L 32 F image": ("F", "F;32"),
  69. # old p3cfunc formats
  70. "RGB3 image": ("RGB", "RGB;T"),
  71. "RYB3 image": ("RGB", "RYB;T"),
  72. # extensions
  73. "LA image": ("LA", "LA;L"),
  74. "PA image": ("LA", "PA;L"),
  75. "RGBA image": ("RGBA", "RGBA;L"),
  76. "RGBX image": ("RGB", "RGBX;L"),
  77. "CMYK image": ("CMYK", "CMYK;L"),
  78. "YCC image": ("YCbCr", "YCbCr;L"),
  79. }
  80. # ifunc95 extensions
  81. for i in ["8", "8S", "16", "16S", "32", "32F"]:
  82. OPEN[f"L {i} image"] = ("F", f"F;{i}")
  83. OPEN[f"L*{i} image"] = ("F", f"F;{i}")
  84. for i in ["16", "16L", "16B"]:
  85. OPEN[f"L {i} image"] = (f"I;{i}", f"I;{i}")
  86. OPEN[f"L*{i} image"] = (f"I;{i}", f"I;{i}")
  87. for i in ["32S"]:
  88. OPEN[f"L {i} image"] = ("I", f"I;{i}")
  89. OPEN[f"L*{i} image"] = ("I", f"I;{i}")
  90. for j in range(2, 33):
  91. OPEN[f"L*{j} image"] = ("F", f"F;{j}")
  92. # --------------------------------------------------------------------
  93. # Read IM directory
  94. split = re.compile(rb"^([A-Za-z][^:]*):[ \t]*(.*)[ \t]*$")
  95. def number(s: Any) -> float:
  96. try:
  97. return int(s)
  98. except ValueError:
  99. return float(s)
  100. ##
  101. # Image plugin for the IFUNC IM file format.
  102. class ImImageFile(ImageFile.ImageFile):
  103. format = "IM"
  104. format_description = "IFUNC Image Memory"
  105. _close_exclusive_fp_after_loading = False
  106. def _open(self) -> None:
  107. # Quick rejection: if there's not an LF among the first
  108. # 100 bytes, this is (probably) not a text header.
  109. if b"\n" not in self.fp.read(100):
  110. msg = "not an IM file"
  111. raise SyntaxError(msg)
  112. self.fp.seek(0)
  113. n = 0
  114. # Default values
  115. self.info[MODE] = "L"
  116. self.info[SIZE] = (512, 512)
  117. self.info[FRAMES] = 1
  118. self.rawmode = "L"
  119. while True:
  120. s = self.fp.read(1)
  121. # Some versions of IFUNC uses \n\r instead of \r\n...
  122. if s == b"\r":
  123. continue
  124. if not s or s == b"\0" or s == b"\x1A":
  125. break
  126. # FIXME: this may read whole file if not a text file
  127. s = s + self.fp.readline()
  128. if len(s) > 100:
  129. msg = "not an IM file"
  130. raise SyntaxError(msg)
  131. if s[-2:] == b"\r\n":
  132. s = s[:-2]
  133. elif s[-1:] == b"\n":
  134. s = s[:-1]
  135. try:
  136. m = split.match(s)
  137. except re.error as e:
  138. msg = "not an IM file"
  139. raise SyntaxError(msg) from e
  140. if m:
  141. k, v = m.group(1, 2)
  142. # Don't know if this is the correct encoding,
  143. # but a decent guess (I guess)
  144. k = k.decode("latin-1", "replace")
  145. v = v.decode("latin-1", "replace")
  146. # Convert value as appropriate
  147. if k in [FRAMES, SCALE, SIZE]:
  148. v = v.replace("*", ",")
  149. v = tuple(map(number, v.split(",")))
  150. if len(v) == 1:
  151. v = v[0]
  152. elif k == MODE and v in OPEN:
  153. v, self.rawmode = OPEN[v]
  154. # Add to dictionary. Note that COMMENT tags are
  155. # combined into a list of strings.
  156. if k == COMMENT:
  157. if k in self.info:
  158. self.info[k].append(v)
  159. else:
  160. self.info[k] = [v]
  161. else:
  162. self.info[k] = v
  163. if k in TAGS:
  164. n += 1
  165. else:
  166. msg = f"Syntax error in IM header: {s.decode('ascii', 'replace')}"
  167. raise SyntaxError(msg)
  168. if not n:
  169. msg = "Not an IM file"
  170. raise SyntaxError(msg)
  171. # Basic attributes
  172. self._size = self.info[SIZE]
  173. self._mode = self.info[MODE]
  174. # Skip forward to start of image data
  175. while s and s[:1] != b"\x1A":
  176. s = self.fp.read(1)
  177. if not s:
  178. msg = "File truncated"
  179. raise SyntaxError(msg)
  180. if LUT in self.info:
  181. # convert lookup table to palette or lut attribute
  182. palette = self.fp.read(768)
  183. greyscale = 1 # greyscale palette
  184. linear = 1 # linear greyscale palette
  185. for i in range(256):
  186. if palette[i] == palette[i + 256] == palette[i + 512]:
  187. if palette[i] != i:
  188. linear = 0
  189. else:
  190. greyscale = 0
  191. if self.mode in ["L", "LA", "P", "PA"]:
  192. if greyscale:
  193. if not linear:
  194. self.lut = list(palette[:256])
  195. else:
  196. if self.mode in ["L", "P"]:
  197. self._mode = self.rawmode = "P"
  198. elif self.mode in ["LA", "PA"]:
  199. self._mode = "PA"
  200. self.rawmode = "PA;L"
  201. self.palette = ImagePalette.raw("RGB;L", palette)
  202. elif self.mode == "RGB":
  203. if not greyscale or not linear:
  204. self.lut = list(palette)
  205. self.frame = 0
  206. self.__offset = offs = self.fp.tell()
  207. self._fp = self.fp # FIXME: hack
  208. if self.rawmode[:2] == "F;":
  209. # ifunc95 formats
  210. try:
  211. # use bit decoder (if necessary)
  212. bits = int(self.rawmode[2:])
  213. if bits not in [8, 16, 32]:
  214. self.tile = [
  215. ImageFile._Tile(
  216. "bit", (0, 0) + self.size, offs, (bits, 8, 3, 0, -1)
  217. )
  218. ]
  219. return
  220. except ValueError:
  221. pass
  222. if self.rawmode in ["RGB;T", "RYB;T"]:
  223. # Old LabEye/3PC files. Would be very surprised if anyone
  224. # ever stumbled upon such a file ;-)
  225. size = self.size[0] * self.size[1]
  226. self.tile = [
  227. ImageFile._Tile("raw", (0, 0) + self.size, offs, ("G", 0, -1)),
  228. ImageFile._Tile("raw", (0, 0) + self.size, offs + size, ("R", 0, -1)),
  229. ImageFile._Tile(
  230. "raw", (0, 0) + self.size, offs + 2 * size, ("B", 0, -1)
  231. ),
  232. ]
  233. else:
  234. # LabEye/IFUNC files
  235. self.tile = [
  236. ImageFile._Tile("raw", (0, 0) + self.size, offs, (self.rawmode, 0, -1))
  237. ]
  238. @property
  239. def n_frames(self) -> int:
  240. return self.info[FRAMES]
  241. @property
  242. def is_animated(self) -> bool:
  243. return self.info[FRAMES] > 1
  244. def seek(self, frame: int) -> None:
  245. if not self._seek_check(frame):
  246. return
  247. self.frame = frame
  248. if self.mode == "1":
  249. bits = 1
  250. else:
  251. bits = 8 * len(self.mode)
  252. size = ((self.size[0] * bits + 7) // 8) * self.size[1]
  253. offs = self.__offset + frame * size
  254. self.fp = self._fp
  255. self.tile = [
  256. ImageFile._Tile("raw", (0, 0) + self.size, offs, (self.rawmode, 0, -1))
  257. ]
  258. def tell(self) -> int:
  259. return self.frame
  260. #
  261. # --------------------------------------------------------------------
  262. # Save IM files
  263. SAVE = {
  264. # mode: (im type, raw mode)
  265. "1": ("0 1", "1"),
  266. "L": ("Greyscale", "L"),
  267. "LA": ("LA", "LA;L"),
  268. "P": ("Greyscale", "P"),
  269. "PA": ("LA", "PA;L"),
  270. "I": ("L 32S", "I;32S"),
  271. "I;16": ("L 16", "I;16"),
  272. "I;16L": ("L 16L", "I;16L"),
  273. "I;16B": ("L 16B", "I;16B"),
  274. "F": ("L 32F", "F;32F"),
  275. "RGB": ("RGB", "RGB;L"),
  276. "RGBA": ("RGBA", "RGBA;L"),
  277. "RGBX": ("RGBX", "RGBX;L"),
  278. "CMYK": ("CMYK", "CMYK;L"),
  279. "YCbCr": ("YCC", "YCbCr;L"),
  280. }
  281. def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
  282. try:
  283. image_type, rawmode = SAVE[im.mode]
  284. except KeyError as e:
  285. msg = f"Cannot save {im.mode} images as IM"
  286. raise ValueError(msg) from e
  287. frames = im.encoderinfo.get("frames", 1)
  288. fp.write(f"Image type: {image_type} image\r\n".encode("ascii"))
  289. if filename:
  290. # Each line must be 100 characters or less,
  291. # or: SyntaxError("not an IM file")
  292. # 8 characters are used for "Name: " and "\r\n"
  293. # Keep just the filename, ditch the potentially overlong path
  294. if isinstance(filename, bytes):
  295. filename = filename.decode("ascii")
  296. name, ext = os.path.splitext(os.path.basename(filename))
  297. name = "".join([name[: 92 - len(ext)], ext])
  298. fp.write(f"Name: {name}\r\n".encode("ascii"))
  299. fp.write(f"Image size (x*y): {im.size[0]}*{im.size[1]}\r\n".encode("ascii"))
  300. fp.write(f"File size (no of images): {frames}\r\n".encode("ascii"))
  301. if im.mode in ["P", "PA"]:
  302. fp.write(b"Lut: 1\r\n")
  303. fp.write(b"\000" * (511 - fp.tell()) + b"\032")
  304. if im.mode in ["P", "PA"]:
  305. im_palette = im.im.getpalette("RGB", "RGB;L")
  306. colors = len(im_palette) // 3
  307. palette = b""
  308. for i in range(3):
  309. palette += im_palette[colors * i : colors * (i + 1)]
  310. palette += b"\x00" * (256 - colors)
  311. fp.write(palette) # 768 bytes
  312. ImageFile._save(
  313. im, fp, [ImageFile._Tile("raw", (0, 0) + im.size, 0, (rawmode, 0, -1))]
  314. )
  315. #
  316. # --------------------------------------------------------------------
  317. # Registry
  318. Image.register_open(ImImageFile.format, ImImageFile)
  319. Image.register_save(ImImageFile.format, _save)
  320. Image.register_extension(ImImageFile.format, ".im")