ImImagePlugin.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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 re
  28. from . import Image, ImageFile, ImagePalette
  29. from ._binary import i8
  30. # __version__ is deprecated and will be removed in a future version. Use
  31. # PIL.__version__ instead.
  32. __version__ = "0.7"
  33. # --------------------------------------------------------------------
  34. # Standard tags
  35. COMMENT = "Comment"
  36. DATE = "Date"
  37. EQUIPMENT = "Digitalization equipment"
  38. FRAMES = "File size (no of images)"
  39. LUT = "Lut"
  40. NAME = "Name"
  41. SCALE = "Scale (x,y)"
  42. SIZE = "Image size (x*y)"
  43. MODE = "Image type"
  44. TAGS = {
  45. COMMENT: 0,
  46. DATE: 0,
  47. EQUIPMENT: 0,
  48. FRAMES: 0,
  49. LUT: 0,
  50. NAME: 0,
  51. SCALE: 0,
  52. SIZE: 0,
  53. MODE: 0,
  54. }
  55. OPEN = {
  56. # ifunc93/p3cfunc formats
  57. "0 1 image": ("1", "1"),
  58. "L 1 image": ("1", "1"),
  59. "Greyscale image": ("L", "L"),
  60. "Grayscale image": ("L", "L"),
  61. "RGB image": ("RGB", "RGB;L"),
  62. "RLB image": ("RGB", "RLB"),
  63. "RYB image": ("RGB", "RLB"),
  64. "B1 image": ("1", "1"),
  65. "B2 image": ("P", "P;2"),
  66. "B4 image": ("P", "P;4"),
  67. "X 24 image": ("RGB", "RGB"),
  68. "L 32 S image": ("I", "I;32"),
  69. "L 32 F image": ("F", "F;32"),
  70. # old p3cfunc formats
  71. "RGB3 image": ("RGB", "RGB;T"),
  72. "RYB3 image": ("RGB", "RYB;T"),
  73. # extensions
  74. "LA image": ("LA", "LA;L"),
  75. "PA image": ("LA", "PA;L"),
  76. "RGBA image": ("RGBA", "RGBA;L"),
  77. "RGBX image": ("RGBX", "RGBX;L"),
  78. "CMYK image": ("CMYK", "CMYK;L"),
  79. "YCC image": ("YCbCr", "YCbCr;L"),
  80. }
  81. # ifunc95 extensions
  82. for i in ["8", "8S", "16", "16S", "32", "32F"]:
  83. OPEN["L %s image" % i] = ("F", "F;%s" % i)
  84. OPEN["L*%s image" % i] = ("F", "F;%s" % i)
  85. for i in ["16", "16L", "16B"]:
  86. OPEN["L %s image" % i] = ("I;%s" % i, "I;%s" % i)
  87. OPEN["L*%s image" % i] = ("I;%s" % i, "I;%s" % i)
  88. for i in ["32S"]:
  89. OPEN["L %s image" % i] = ("I", "I;%s" % i)
  90. OPEN["L*%s image" % i] = ("I", "I;%s" % i)
  91. for i in range(2, 33):
  92. OPEN["L*%s image" % i] = ("F", "F;%s" % i)
  93. # --------------------------------------------------------------------
  94. # Read IM directory
  95. split = re.compile(br"^([A-Za-z][^:]*):[ \t]*(.*)[ \t]*$")
  96. def number(s):
  97. try:
  98. return int(s)
  99. except ValueError:
  100. return float(s)
  101. ##
  102. # Image plugin for the IFUNC IM file format.
  103. class ImImageFile(ImageFile.ImageFile):
  104. format = "IM"
  105. format_description = "IFUNC Image Memory"
  106. _close_exclusive_fp_after_loading = False
  107. def _open(self):
  108. # Quick rejection: if there's not an LF among the first
  109. # 100 bytes, this is (probably) not a text header.
  110. if b"\n" not in self.fp.read(100):
  111. raise SyntaxError("not an IM file")
  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. raise SyntaxError("not an IM file")
  130. if s[-2:] == b"\r\n":
  131. s = s[:-2]
  132. elif s[-1:] == b"\n":
  133. s = s[:-1]
  134. try:
  135. m = split.match(s)
  136. except re.error:
  137. raise SyntaxError("not an IM file")
  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. raise SyntaxError(
  165. "Syntax error in IM header: " + s.decode("ascii", "replace")
  166. )
  167. if not n:
  168. raise SyntaxError("Not an IM file")
  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[0:1] != b"\x1A":
  174. s = self.fp.read(1)
  175. if not s:
  176. raise SyntaxError("File truncated")
  177. if LUT in self.info:
  178. # convert lookup table to palette or lut attribute
  179. palette = self.fp.read(768)
  180. greyscale = 1 # greyscale palette
  181. linear = 1 # linear greyscale palette
  182. for i in range(256):
  183. if palette[i] == palette[i + 256] == palette[i + 512]:
  184. if i8(palette[i]) != i:
  185. linear = 0
  186. else:
  187. greyscale = 0
  188. if self.mode in ["L", "LA", "P", "PA"]:
  189. if greyscale:
  190. if not linear:
  191. self.lut = [i8(c) for c in palette[:256]]
  192. else:
  193. if self.mode in ["L", "P"]:
  194. self.mode = self.rawmode = "P"
  195. elif self.mode in ["LA", "PA"]:
  196. self.mode = "PA"
  197. self.rawmode = "PA;L"
  198. self.palette = ImagePalette.raw("RGB;L", palette)
  199. elif self.mode == "RGB":
  200. if not greyscale or not linear:
  201. self.lut = [i8(c) for c in palette]
  202. self.frame = 0
  203. self.__offset = offs = self.fp.tell()
  204. self.__fp = self.fp # FIXME: hack
  205. if self.rawmode[:2] == "F;":
  206. # ifunc95 formats
  207. try:
  208. # use bit decoder (if necessary)
  209. bits = int(self.rawmode[2:])
  210. if bits not in [8, 16, 32]:
  211. self.tile = [("bit", (0, 0) + self.size, offs, (bits, 8, 3, 0, -1))]
  212. return
  213. except ValueError:
  214. pass
  215. if self.rawmode in ["RGB;T", "RYB;T"]:
  216. # Old LabEye/3PC files. Would be very surprised if anyone
  217. # ever stumbled upon such a file ;-)
  218. size = self.size[0] * self.size[1]
  219. self.tile = [
  220. ("raw", (0, 0) + self.size, offs, ("G", 0, -1)),
  221. ("raw", (0, 0) + self.size, offs + size, ("R", 0, -1)),
  222. ("raw", (0, 0) + self.size, offs + 2 * size, ("B", 0, -1)),
  223. ]
  224. else:
  225. # LabEye/IFUNC files
  226. self.tile = [("raw", (0, 0) + self.size, offs, (self.rawmode, 0, -1))]
  227. @property
  228. def n_frames(self):
  229. return self.info[FRAMES]
  230. @property
  231. def is_animated(self):
  232. return self.info[FRAMES] > 1
  233. def seek(self, frame):
  234. if not self._seek_check(frame):
  235. return
  236. self.frame = frame
  237. if self.mode == "1":
  238. bits = 1
  239. else:
  240. bits = 8 * len(self.mode)
  241. size = ((self.size[0] * bits + 7) // 8) * self.size[1]
  242. offs = self.__offset + frame * size
  243. self.fp = self.__fp
  244. self.tile = [("raw", (0, 0) + self.size, offs, (self.rawmode, 0, -1))]
  245. def tell(self):
  246. return self.frame
  247. def _close__fp(self):
  248. try:
  249. if self.__fp != self.fp:
  250. self.__fp.close()
  251. except AttributeError:
  252. pass
  253. finally:
  254. self.__fp = None
  255. #
  256. # --------------------------------------------------------------------
  257. # Save IM files
  258. SAVE = {
  259. # mode: (im type, raw mode)
  260. "1": ("0 1", "1"),
  261. "L": ("Greyscale", "L"),
  262. "LA": ("LA", "LA;L"),
  263. "P": ("Greyscale", "P"),
  264. "PA": ("LA", "PA;L"),
  265. "I": ("L 32S", "I;32S"),
  266. "I;16": ("L 16", "I;16"),
  267. "I;16L": ("L 16L", "I;16L"),
  268. "I;16B": ("L 16B", "I;16B"),
  269. "F": ("L 32F", "F;32F"),
  270. "RGB": ("RGB", "RGB;L"),
  271. "RGBA": ("RGBA", "RGBA;L"),
  272. "RGBX": ("RGBX", "RGBX;L"),
  273. "CMYK": ("CMYK", "CMYK;L"),
  274. "YCbCr": ("YCC", "YCbCr;L"),
  275. }
  276. def _save(im, fp, filename):
  277. try:
  278. image_type, rawmode = SAVE[im.mode]
  279. except KeyError:
  280. raise ValueError("Cannot save %s images as IM" % im.mode)
  281. frames = im.encoderinfo.get("frames", 1)
  282. fp.write(("Image type: %s image\r\n" % image_type).encode("ascii"))
  283. if filename:
  284. fp.write(("Name: %s\r\n" % filename).encode("ascii"))
  285. fp.write(("Image size (x*y): %d*%d\r\n" % im.size).encode("ascii"))
  286. fp.write(("File size (no of images): %d\r\n" % frames).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. fp.write(im.im.getpalette("RGB", "RGB;L")) # 768 bytes
  292. ImageFile._save(im, fp, [("raw", (0, 0) + im.size, 0, (rawmode, 0, -1))])
  293. #
  294. # --------------------------------------------------------------------
  295. # Registry
  296. Image.register_open(ImImageFile.format, ImImageFile)
  297. Image.register_save(ImImageFile.format, _save)
  298. Image.register_extension(ImImageFile.format, ".im")