Coverage for /var/srv/projects/api.amasfac.comuna18.com/tmp/venv/lib/python3.9/site-packages/PIL/BmpImagePlugin.py: 17%
187 statements
« prev ^ index » next coverage.py v6.4.4, created at 2023-07-17 14:22 -0600
« prev ^ index » next coverage.py v6.4.4, created at 2023-07-17 14:22 -0600
1#
2# The Python Imaging Library.
3# $Id$
4#
5# BMP file handler
6#
7# Windows (and OS/2) native bitmap storage format.
8#
9# history:
10# 1995-09-01 fl Created
11# 1996-04-30 fl Added save
12# 1997-08-27 fl Fixed save of 1-bit images
13# 1998-03-06 fl Load P images as L where possible
14# 1998-07-03 fl Load P images as 1 where possible
15# 1998-12-29 fl Handle small palettes
16# 2002-12-30 fl Fixed load of 1-bit palette images
17# 2003-04-21 fl Fixed load of 1-bit monochrome images
18# 2003-04-23 fl Added limited support for BI_BITFIELDS compression
19#
20# Copyright (c) 1997-2003 by Secret Labs AB
21# Copyright (c) 1995-2003 by Fredrik Lundh
22#
23# See the README file for information on usage and redistribution.
24#
27import os
29from . import Image, ImageFile, ImagePalette
30from ._binary import i16le as i16
31from ._binary import i32le as i32
32from ._binary import o8
33from ._binary import o16le as o16
34from ._binary import o32le as o32
36#
37# --------------------------------------------------------------------
38# Read BMP file
40BIT2MODE = {
41 # bits => mode, rawmode
42 1: ("P", "P;1"),
43 4: ("P", "P;4"),
44 8: ("P", "P"),
45 16: ("RGB", "BGR;15"),
46 24: ("RGB", "BGR"),
47 32: ("RGB", "BGRX"),
48}
51def _accept(prefix):
52 return prefix[:2] == b"BM"
55def _dib_accept(prefix):
56 return i32(prefix) in [12, 40, 64, 108, 124]
59# =============================================================================
60# Image plugin for the Windows BMP format.
61# =============================================================================
62class BmpImageFile(ImageFile.ImageFile):
63 """Image plugin for the Windows Bitmap format (BMP)"""
65 # ------------------------------------------------------------- Description
66 format_description = "Windows Bitmap"
67 format = "BMP"
69 # -------------------------------------------------- BMP Compression values
70 COMPRESSIONS = {"RAW": 0, "RLE8": 1, "RLE4": 2, "BITFIELDS": 3, "JPEG": 4, "PNG": 5}
71 for k, v in COMPRESSIONS.items():
72 vars()[k] = v
74 def _bitmap(self, header=0, offset=0):
75 """Read relevant info about the BMP"""
76 read, seek = self.fp.read, self.fp.seek
77 if header:
78 seek(header)
79 # read bmp header size @offset 14 (this is part of the header size)
80 file_info = {"header_size": i32(read(4)), "direction": -1}
82 # -------------------- If requested, read header at a specific position
83 # read the rest of the bmp header, without its size
84 header_data = ImageFile._safe_read(self.fp, file_info["header_size"] - 4)
86 # -------------------------------------------------- IBM OS/2 Bitmap v1
87 # ----- This format has different offsets because of width/height types
88 if file_info["header_size"] == 12:
89 file_info["width"] = i16(header_data, 0)
90 file_info["height"] = i16(header_data, 2)
91 file_info["planes"] = i16(header_data, 4)
92 file_info["bits"] = i16(header_data, 6)
93 file_info["compression"] = self.RAW
94 file_info["palette_padding"] = 3
96 # --------------------------------------------- Windows Bitmap v2 to v5
97 # v3, OS/2 v2, v4, v5
98 elif file_info["header_size"] in (40, 64, 108, 124):
99 file_info["y_flip"] = header_data[7] == 0xFF
100 file_info["direction"] = 1 if file_info["y_flip"] else -1
101 file_info["width"] = i32(header_data, 0)
102 file_info["height"] = (
103 i32(header_data, 4)
104 if not file_info["y_flip"]
105 else 2**32 - i32(header_data, 4)
106 )
107 file_info["planes"] = i16(header_data, 8)
108 file_info["bits"] = i16(header_data, 10)
109 file_info["compression"] = i32(header_data, 12)
110 # byte size of pixel data
111 file_info["data_size"] = i32(header_data, 16)
112 file_info["pixels_per_meter"] = (
113 i32(header_data, 20),
114 i32(header_data, 24),
115 )
116 file_info["colors"] = i32(header_data, 28)
117 file_info["palette_padding"] = 4
118 self.info["dpi"] = tuple(x / 39.3701 for x in file_info["pixels_per_meter"])
119 if file_info["compression"] == self.BITFIELDS:
120 if len(header_data) >= 52:
121 for idx, mask in enumerate(
122 ["r_mask", "g_mask", "b_mask", "a_mask"]
123 ):
124 file_info[mask] = i32(header_data, 36 + idx * 4)
125 else:
126 # 40 byte headers only have the three components in the
127 # bitfields masks, ref:
128 # https://msdn.microsoft.com/en-us/library/windows/desktop/dd183376(v=vs.85).aspx
129 # See also
130 # https://github.com/python-pillow/Pillow/issues/1293
131 # There is a 4th component in the RGBQuad, in the alpha
132 # location, but it is listed as a reserved component,
133 # and it is not generally an alpha channel
134 file_info["a_mask"] = 0x0
135 for mask in ["r_mask", "g_mask", "b_mask"]:
136 file_info[mask] = i32(read(4))
137 file_info["rgb_mask"] = (
138 file_info["r_mask"],
139 file_info["g_mask"],
140 file_info["b_mask"],
141 )
142 file_info["rgba_mask"] = (
143 file_info["r_mask"],
144 file_info["g_mask"],
145 file_info["b_mask"],
146 file_info["a_mask"],
147 )
148 else:
149 raise OSError(f"Unsupported BMP header type ({file_info['header_size']})")
151 # ------------------ Special case : header is reported 40, which
152 # ---------------------- is shorter than real size for bpp >= 16
153 self._size = file_info["width"], file_info["height"]
155 # ------- If color count was not found in the header, compute from bits
156 file_info["colors"] = (
157 file_info["colors"]
158 if file_info.get("colors", 0)
159 else (1 << file_info["bits"])
160 )
161 if offset == 14 + file_info["header_size"] and file_info["bits"] <= 8:
162 offset += 4 * file_info["colors"]
164 # ---------------------- Check bit depth for unusual unsupported values
165 self.mode, raw_mode = BIT2MODE.get(file_info["bits"], (None, None))
166 if self.mode is None:
167 raise OSError(f"Unsupported BMP pixel depth ({file_info['bits']})")
169 # ---------------- Process BMP with Bitfields compression (not palette)
170 decoder_name = "raw"
171 if file_info["compression"] == self.BITFIELDS:
172 SUPPORTED = {
173 32: [
174 (0xFF0000, 0xFF00, 0xFF, 0x0),
175 (0xFF0000, 0xFF00, 0xFF, 0xFF000000),
176 (0xFF, 0xFF00, 0xFF0000, 0xFF000000),
177 (0x0, 0x0, 0x0, 0x0),
178 (0xFF000000, 0xFF0000, 0xFF00, 0x0),
179 ],
180 24: [(0xFF0000, 0xFF00, 0xFF)],
181 16: [(0xF800, 0x7E0, 0x1F), (0x7C00, 0x3E0, 0x1F)],
182 }
183 MASK_MODES = {
184 (32, (0xFF0000, 0xFF00, 0xFF, 0x0)): "BGRX",
185 (32, (0xFF000000, 0xFF0000, 0xFF00, 0x0)): "XBGR",
186 (32, (0xFF, 0xFF00, 0xFF0000, 0xFF000000)): "RGBA",
187 (32, (0xFF0000, 0xFF00, 0xFF, 0xFF000000)): "BGRA",
188 (32, (0x0, 0x0, 0x0, 0x0)): "BGRA",
189 (24, (0xFF0000, 0xFF00, 0xFF)): "BGR",
190 (16, (0xF800, 0x7E0, 0x1F)): "BGR;16",
191 (16, (0x7C00, 0x3E0, 0x1F)): "BGR;15",
192 }
193 if file_info["bits"] in SUPPORTED:
194 if (
195 file_info["bits"] == 32
196 and file_info["rgba_mask"] in SUPPORTED[file_info["bits"]]
197 ):
198 raw_mode = MASK_MODES[(file_info["bits"], file_info["rgba_mask"])]
199 self.mode = "RGBA" if "A" in raw_mode else self.mode
200 elif (
201 file_info["bits"] in (24, 16)
202 and file_info["rgb_mask"] in SUPPORTED[file_info["bits"]]
203 ):
204 raw_mode = MASK_MODES[(file_info["bits"], file_info["rgb_mask"])]
205 else:
206 raise OSError("Unsupported BMP bitfields layout")
207 else:
208 raise OSError("Unsupported BMP bitfields layout")
209 elif file_info["compression"] == self.RAW:
210 if file_info["bits"] == 32 and header == 22: # 32-bit .cur offset
211 raw_mode, self.mode = "BGRA", "RGBA"
212 elif file_info["compression"] == self.RLE8:
213 decoder_name = "bmp_rle"
214 else:
215 raise OSError(f"Unsupported BMP compression ({file_info['compression']})")
217 # --------------- Once the header is processed, process the palette/LUT
218 if self.mode == "P": # Paletted for 1, 4 and 8 bit images
220 # ---------------------------------------------------- 1-bit images
221 if not (0 < file_info["colors"] <= 65536):
222 raise OSError(f"Unsupported BMP Palette size ({file_info['colors']})")
223 else:
224 padding = file_info["palette_padding"]
225 palette = read(padding * file_info["colors"])
226 greyscale = True
227 indices = (
228 (0, 255)
229 if file_info["colors"] == 2
230 else list(range(file_info["colors"]))
231 )
233 # ----------------- Check if greyscale and ignore palette if so
234 for ind, val in enumerate(indices):
235 rgb = palette[ind * padding : ind * padding + 3]
236 if rgb != o8(val) * 3:
237 greyscale = False
239 # ------- If all colors are grey, white or black, ditch palette
240 if greyscale:
241 self.mode = "1" if file_info["colors"] == 2 else "L"
242 raw_mode = self.mode
243 else:
244 self.mode = "P"
245 self.palette = ImagePalette.raw(
246 "BGRX" if padding == 4 else "BGR", palette
247 )
249 # ---------------------------- Finally set the tile data for the plugin
250 self.info["compression"] = file_info["compression"]
251 self.tile = [
252 (
253 decoder_name,
254 (0, 0, file_info["width"], file_info["height"]),
255 offset or self.fp.tell(),
256 (
257 raw_mode,
258 ((file_info["width"] * file_info["bits"] + 31) >> 3) & (~3),
259 file_info["direction"],
260 ),
261 )
262 ]
264 def _open(self):
265 """Open file, check magic number and read header"""
266 # read 14 bytes: magic number, filesize, reserved, header final offset
267 head_data = self.fp.read(14)
268 # choke if the file does not have the required magic bytes
269 if not _accept(head_data):
270 raise SyntaxError("Not a BMP file")
271 # read the start position of the BMP image data (u32)
272 offset = i32(head_data, 10)
273 # load bitmap information (offset=raster info)
274 self._bitmap(offset=offset)
277class BmpRleDecoder(ImageFile.PyDecoder):
278 _pulls_fd = True
280 def decode(self, buffer):
281 data = bytearray()
282 x = 0
283 while len(data) < self.state.xsize * self.state.ysize:
284 pixels = self.fd.read(1)
285 byte = self.fd.read(1)
286 if not pixels or not byte:
287 break
288 num_pixels = pixels[0]
289 if num_pixels:
290 # encoded mode
291 if x + num_pixels > self.state.xsize:
292 # Too much data for row
293 num_pixels = max(0, self.state.xsize - x)
294 data += byte * num_pixels
295 x += num_pixels
296 else:
297 if byte[0] == 0:
298 # end of line
299 while len(data) % self.state.xsize != 0:
300 data += b"\x00"
301 x = 0
302 elif byte[0] == 1:
303 # end of bitmap
304 break
305 elif byte[0] == 2:
306 # delta
307 bytes_read = self.fd.read(2)
308 if len(bytes_read) < 2:
309 break
310 right, up = self.fd.read(2)
311 data += b"\x00" * (right + up * self.state.xsize)
312 x = len(data) % self.state.xsize
313 else:
314 # absolute mode
315 bytes_read = self.fd.read(byte[0])
316 data += bytes_read
317 if len(bytes_read) < byte[0]:
318 break
319 x += byte[0]
321 # align to 16-bit word boundary
322 if self.fd.tell() % 2 != 0:
323 self.fd.seek(1, os.SEEK_CUR)
324 rawmode = "L" if self.mode == "L" else "P"
325 self.set_as_raw(bytes(data), (rawmode, 0, self.args[-1]))
326 return -1, 0
329# =============================================================================
330# Image plugin for the DIB format (BMP alias)
331# =============================================================================
332class DibImageFile(BmpImageFile):
334 format = "DIB"
335 format_description = "Windows Bitmap"
337 def _open(self):
338 self._bitmap()
341#
342# --------------------------------------------------------------------
343# Write BMP file
346SAVE = {
347 "1": ("1", 1, 2),
348 "L": ("L", 8, 256),
349 "P": ("P", 8, 256),
350 "RGB": ("BGR", 24, 0),
351 "RGBA": ("BGRA", 32, 0),
352}
355def _dib_save(im, fp, filename):
356 _save(im, fp, filename, False)
359def _save(im, fp, filename, bitmap_header=True):
360 try:
361 rawmode, bits, colors = SAVE[im.mode]
362 except KeyError as e:
363 raise OSError(f"cannot write mode {im.mode} as BMP") from e
365 info = im.encoderinfo
367 dpi = info.get("dpi", (96, 96))
369 # 1 meter == 39.3701 inches
370 ppm = tuple(map(lambda x: int(x * 39.3701 + 0.5), dpi))
372 stride = ((im.size[0] * bits + 7) // 8 + 3) & (~3)
373 header = 40 # or 64 for OS/2 version 2
374 image = stride * im.size[1]
376 # bitmap header
377 if bitmap_header:
378 offset = 14 + header + colors * 4
379 file_size = offset + image
380 if file_size > 2**32 - 1:
381 raise ValueError("File size is too large for the BMP format")
382 fp.write(
383 b"BM" # file type (magic)
384 + o32(file_size) # file size
385 + o32(0) # reserved
386 + o32(offset) # image data offset
387 )
389 # bitmap info header
390 fp.write(
391 o32(header) # info header size
392 + o32(im.size[0]) # width
393 + o32(im.size[1]) # height
394 + o16(1) # planes
395 + o16(bits) # depth
396 + o32(0) # compression (0=uncompressed)
397 + o32(image) # size of bitmap
398 + o32(ppm[0]) # resolution
399 + o32(ppm[1]) # resolution
400 + o32(colors) # colors used
401 + o32(colors) # colors important
402 )
404 fp.write(b"\0" * (header - 40)) # padding (for OS/2 format)
406 if im.mode == "1":
407 for i in (0, 255):
408 fp.write(o8(i) * 4)
409 elif im.mode == "L":
410 for i in range(256):
411 fp.write(o8(i) * 4)
412 elif im.mode == "P":
413 fp.write(im.im.getpalette("RGB", "BGRX"))
415 ImageFile._save(im, fp, [("raw", (0, 0) + im.size, 0, (rawmode, stride, -1))])
418#
419# --------------------------------------------------------------------
420# Registry
423Image.register_open(BmpImageFile.format, BmpImageFile, _accept)
424Image.register_save(BmpImageFile.format, _save)
426Image.register_extension(BmpImageFile.format, ".bmp")
428Image.register_mime(BmpImageFile.format, "image/bmp")
430Image.register_decoder("bmp_rle", BmpRleDecoder)
432Image.register_open(DibImageFile.format, DibImageFile, _dib_accept)
433Image.register_save(DibImageFile.format, _dib_save)
435Image.register_extension(DibImageFile.format, ".dib")
437Image.register_mime(DibImageFile.format, "image/bmp")