ImImagePlugin.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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(br"^([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. raise SyntaxError("not an IM file")
  109. self.fp.seek(0)
  110. n = 0
  111. # Default values
  112. self.info[MODE] = "L"
  113. self.info[SIZE] = (512, 512)
  114. self.info[FRAMES] = 1
  115. self.rawmode = "L"
  116. while True:
  117. s = self.fp.read(1)
  118. # Some versions of IFUNC uses \n\r instead of \r\n...
  119. if s == b"\r":
  120. continue
  121. if not s or s == b"\0" or s == b"\x1A":
  122. break
  123. # FIXME: this may read whole file if not a text file
  124. s = s + self.fp.readline()
  125. if len(s) > 100:
  126. raise SyntaxError("not an IM file")
  127. if s[-2:] == b"\r\n":
  128. s = s[:-2]
  129. elif s[-1:] == b"\n":
  130. s = s[:-1]
  131. try:
  132. m = split.match(s)
  133. except re.error as e:
  134. raise SyntaxError("not an IM file") from e
  135. if m:
  136. k, v = m.group(1, 2)
  137. # Don't know if this is the correct encoding,
  138. # but a decent guess (I guess)
  139. k = k.decode("latin-1", "replace")
  140. v = v.decode("latin-1", "replace")
  141. # Convert value as appropriate
  142. if k in [FRAMES, SCALE, SIZE]:
  143. v = v.replace("*", ",")
  144. v = tuple(map(number, v.split(",")))
  145. if len(v) == 1:
  146. v = v[0]
  147. elif k == MODE and v in OPEN:
  148. v, self.rawmode = OPEN[v]
  149. # Add to dictionary. Note that COMMENT tags are
  150. # combined into a list of strings.
  151. if k == COMMENT:
  152. if k in self.info:
  153. self.info[k].append(v)
  154. else:
  155. self.info[k] = [v]
  156. else:
  157. self.info[k] = v
  158. if k in TAGS:
  159. n += 1
  160. else:
  161. raise SyntaxError(
  162. "Syntax error in IM header: " + s.decode("ascii", "replace")
  163. )
  164. if not n:
  165. raise SyntaxError("Not an IM file")
  166. # Basic attributes
  167. self._size = self.info[SIZE]
  168. self.mode = self.info[MODE]
  169. # Skip forward to start of image data
  170. while s and s[0:1] != b"\x1A":
  171. s = self.fp.read(1)
  172. if not s:
  173. raise SyntaxError("File truncated")
  174. if LUT in self.info:
  175. # convert lookup table to palette or lut attribute
  176. palette = self.fp.read(768)
  177. greyscale = 1 # greyscale palette
  178. linear = 1 # linear greyscale palette
  179. for i in range(256):
  180. if palette[i] == palette[i + 256] == palette[i + 512]:
  181. if palette[i] != i:
  182. linear = 0
  183. else:
  184. greyscale = 0
  185. if self.mode in ["L", "LA", "P", "PA"]:
  186. if greyscale:
  187. if not linear:
  188. self.lut = list(palette[:256])
  189. else:
  190. if self.mode in ["L", "P"]:
  191. self.mode = self.rawmode = "P"
  192. elif self.mode in ["LA", "PA"]:
  193. self.mode = "PA"
  194. self.rawmode = "PA;L"
  195. self.palette = ImagePalette.raw("RGB;L", palette)
  196. elif self.mode == "RGB":
  197. if not greyscale or not linear:
  198. self.lut = list(palette)
  199. self.frame = 0
  200. self.__offset = offs = self.fp.tell()
  201. self.__fp = self.fp # FIXME: hack
  202. if self.rawmode[:2] == "F;":
  203. # ifunc95 formats
  204. try:
  205. # use bit decoder (if necessary)
  206. bits = int(self.rawmode[2:])
  207. if bits not in [8, 16, 32]:
  208. self.tile = [("bit", (0, 0) + self.size, offs, (bits, 8, 3, 0, -1))]
  209. return
  210. except ValueError:
  211. pass
  212. if self.rawmode in ["RGB;T", "RYB;T"]:
  213. # Old LabEye/3PC files. Would be very surprised if anyone
  214. # ever stumbled upon such a file ;-)
  215. size = self.size[0] * self.size[1]
  216. self.tile = [
  217. ("raw", (0, 0) + self.size, offs, ("G", 0, -1)),
  218. ("raw", (0, 0) + self.size, offs + size, ("R", 0, -1)),
  219. ("raw", (0, 0) + self.size, offs + 2 * size, ("B", 0, -1)),
  220. ]
  221. else:
  222. # LabEye/IFUNC files
  223. self.tile = [("raw", (0, 0) + self.size, offs, (self.rawmode, 0, -1))]
  224. @property
  225. def n_frames(self):
  226. return self.info[FRAMES]
  227. @property
  228. def is_animated(self):
  229. return self.info[FRAMES] > 1
  230. def seek(self, frame):
  231. if not self._seek_check(frame):
  232. return
  233. self.frame = frame
  234. if self.mode == "1":
  235. bits = 1
  236. else:
  237. bits = 8 * len(self.mode)
  238. size = ((self.size[0] * bits + 7) // 8) * self.size[1]
  239. offs = self.__offset + frame * size
  240. self.fp = self.__fp
  241. self.tile = [("raw", (0, 0) + self.size, offs, (self.rawmode, 0, -1))]
  242. def tell(self):
  243. return self.frame
  244. def _close__fp(self):
  245. try:
  246. if self.__fp != self.fp:
  247. self.__fp.close()
  248. except AttributeError:
  249. pass
  250. finally:
  251. self.__fp = None
  252. #
  253. # --------------------------------------------------------------------
  254. # Save IM files
  255. SAVE = {
  256. # mode: (im type, raw mode)
  257. "1": ("0 1", "1"),
  258. "L": ("Greyscale", "L"),
  259. "LA": ("LA", "LA;L"),
  260. "P": ("Greyscale", "P"),
  261. "PA": ("LA", "PA;L"),
  262. "I": ("L 32S", "I;32S"),
  263. "I;16": ("L 16", "I;16"),
  264. "I;16L": ("L 16L", "I;16L"),
  265. "I;16B": ("L 16B", "I;16B"),
  266. "F": ("L 32F", "F;32F"),
  267. "RGB": ("RGB", "RGB;L"),
  268. "RGBA": ("RGBA", "RGBA;L"),
  269. "RGBX": ("RGBX", "RGBX;L"),
  270. "CMYK": ("CMYK", "CMYK;L"),
  271. "YCbCr": ("YCC", "YCbCr;L"),
  272. }
  273. def _save(im, fp, filename):
  274. try:
  275. image_type, rawmode = SAVE[im.mode]
  276. except KeyError as e:
  277. raise ValueError(f"Cannot save {im.mode} images as IM") from e
  278. frames = im.encoderinfo.get("frames", 1)
  279. fp.write(f"Image type: {image_type} image\r\n".encode("ascii"))
  280. if filename:
  281. # Each line must be 100 characters or less,
  282. # or: SyntaxError("not an IM file")
  283. # 8 characters are used for "Name: " and "\r\n"
  284. # Keep just the filename, ditch the potentially overlong path
  285. name, ext = os.path.splitext(os.path.basename(filename))
  286. name = "".join([name[: 92 - len(ext)], ext])
  287. fp.write(f"Name: {name}\r\n".encode("ascii"))
  288. fp.write(("Image size (x*y): %d*%d\r\n" % im.size).encode("ascii"))
  289. fp.write(f"File size (no of images): {frames}\r\n".encode("ascii"))
  290. if im.mode in ["P", "PA"]:
  291. fp.write(b"Lut: 1\r\n")
  292. fp.write(b"\000" * (511 - fp.tell()) + b"\032")
  293. if im.mode in ["P", "PA"]:
  294. fp.write(im.im.getpalette("RGB", "RGB;L")) # 768 bytes
  295. ImageFile._save(im, fp, [("raw", (0, 0) + im.size, 0, (rawmode, 0, -1))])
  296. #
  297. # --------------------------------------------------------------------
  298. # Registry
  299. Image.register_open(ImImageFile.format, ImImageFile)
  300. Image.register_save(ImImageFile.format, _save)
  301. Image.register_extension(ImImageFile.format, ".im")