ImImagePlugin.py 11 KB

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