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