ImImagePlugin.py 12 KB

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