BmpImagePlugin.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  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. #
  25. from __future__ import annotations
  26. __lazy_modules__ = {"PIL._binary"}
  27. import os
  28. from . import Image, ImageFile, ImagePalette
  29. from ._binary import i16le as i16
  30. from ._binary import i32le as i32
  31. from ._binary import o8
  32. from ._binary import o16le as o16
  33. from ._binary import o32le as o32
  34. TYPE_CHECKING = False
  35. if TYPE_CHECKING:
  36. from typing import IO, Any
  37. #
  38. # --------------------------------------------------------------------
  39. # Read BMP file
  40. BIT2MODE = {
  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. }
  49. USE_RAW_ALPHA = False
  50. def _accept(prefix: bytes) -> bool:
  51. return prefix.startswith(b"BM")
  52. def _dib_accept(prefix: bytes) -> bool:
  53. return i32(prefix) in [12, 40, 52, 56, 64, 108, 124]
  54. # =============================================================================
  55. # Image plugin for the Windows BMP format.
  56. # =============================================================================
  57. class BmpImageFile(ImageFile.ImageFile):
  58. """Image plugin for the Windows Bitmap format (BMP)"""
  59. # ------------------------------------------------------------- Description
  60. format_description = "Windows Bitmap"
  61. format = "BMP"
  62. # -------------------------------------------------- BMP Compression values
  63. COMPRESSIONS = {"RAW": 0, "RLE8": 1, "RLE4": 2, "BITFIELDS": 3, "JPEG": 4, "PNG": 5}
  64. for k, v in COMPRESSIONS.items():
  65. vars()[k] = v
  66. def _bitmap(self, header: int = 0, offset: int = 0) -> None:
  67. """Read relevant info about the BMP"""
  68. assert self.fp is not None
  69. read, seek = self.fp.read, self.fp.seek
  70. if header:
  71. seek(header)
  72. # read bmp header size @offset 14 (this is part of the header size)
  73. file_info: dict[str, bool | int | tuple[int, ...]] = {
  74. "header_size": i32(read(4)),
  75. "direction": -1,
  76. }
  77. # -------------------- If requested, read header at a specific position
  78. # read the rest of the bmp header, without its size
  79. assert isinstance(file_info["header_size"], int)
  80. header_data = ImageFile._safe_read(self.fp, file_info["header_size"] - 4)
  81. # ------------------------------- Windows Bitmap v2, IBM OS/2 Bitmap v1
  82. # ----- This format has different offsets because of width/height types
  83. # 12: BITMAPCOREHEADER/OS21XBITMAPHEADER
  84. if file_info["header_size"] == 12:
  85. file_info["width"] = i16(header_data, 0)
  86. file_info["height"] = i16(header_data, 2)
  87. file_info["planes"] = i16(header_data, 4)
  88. file_info["bits"] = i16(header_data, 6)
  89. file_info["compression"] = self.COMPRESSIONS["RAW"]
  90. file_info["palette_padding"] = 3
  91. # --------------------------------------------- Windows Bitmap v3 to v5
  92. # 40: BITMAPINFOHEADER
  93. # 52: BITMAPV2HEADER
  94. # 56: BITMAPV3HEADER
  95. # 64: BITMAPCOREHEADER2/OS22XBITMAPHEADER
  96. # 108: BITMAPV4HEADER
  97. # 124: BITMAPV5HEADER
  98. elif file_info["header_size"] in (40, 52, 56, 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. assert isinstance(file_info["pixels_per_meter"], tuple)
  119. dpi = tuple(x / 39.3701 for x in file_info["pixels_per_meter"])
  120. if dpi != (0, 0):
  121. self.info["dpi"] = dpi
  122. if file_info["compression"] == self.COMPRESSIONS["BITFIELDS"]:
  123. masks = ["r_mask", "g_mask", "b_mask"]
  124. if len(header_data) >= 48:
  125. if len(header_data) >= 52:
  126. masks.append("a_mask")
  127. else:
  128. file_info["a_mask"] = 0x0
  129. for idx, mask in enumerate(masks):
  130. file_info[mask] = i32(header_data, 36 + idx * 4)
  131. else:
  132. # 40 byte headers only have the three components in the
  133. # bitfields masks, ref:
  134. # https://msdn.microsoft.com/en-us/library/windows/desktop/dd183376(v=vs.85).aspx
  135. # See also
  136. # https://github.com/python-pillow/Pillow/issues/1293
  137. # There is a 4th component in the RGBQuad, in the alpha
  138. # location, but it is listed as a reserved component,
  139. # and it is not generally an alpha channel
  140. file_info["a_mask"] = 0x0
  141. for mask in masks:
  142. file_info[mask] = i32(read(4))
  143. assert isinstance(file_info["r_mask"], int)
  144. assert isinstance(file_info["g_mask"], int)
  145. assert isinstance(file_info["b_mask"], int)
  146. assert isinstance(file_info["a_mask"], int)
  147. file_info["rgb_mask"] = (
  148. file_info["r_mask"],
  149. file_info["g_mask"],
  150. file_info["b_mask"],
  151. )
  152. file_info["rgba_mask"] = (
  153. file_info["r_mask"],
  154. file_info["g_mask"],
  155. file_info["b_mask"],
  156. file_info["a_mask"],
  157. )
  158. else:
  159. msg = f"Unsupported BMP header type ({file_info['header_size']})"
  160. raise OSError(msg)
  161. # ------------------ Special case : header is reported 40, which
  162. # ---------------------- is shorter than real size for bpp >= 16
  163. assert isinstance(file_info["width"], int)
  164. assert isinstance(file_info["height"], int)
  165. self._size = file_info["width"], file_info["height"]
  166. # ------- If color count was not found in the header, compute from bits
  167. assert isinstance(file_info["bits"], int)
  168. if not file_info.get("colors", 0):
  169. file_info["colors"] = 1 << file_info["bits"]
  170. assert isinstance(file_info["palette_padding"], int)
  171. assert isinstance(file_info["colors"], int)
  172. if offset == 14 + file_info["header_size"] and file_info["bits"] <= 8:
  173. offset += file_info["palette_padding"] * file_info["colors"]
  174. # ---------------------- Check bit depth for unusual unsupported values
  175. self._mode, raw_mode = BIT2MODE.get(file_info["bits"], ("", ""))
  176. if not self.mode:
  177. msg = f"Unsupported BMP pixel depth ({file_info['bits']})"
  178. raise OSError(msg)
  179. # ---------------- Process BMP with Bitfields compression (not palette)
  180. decoder_name = "raw"
  181. if file_info["compression"] == self.COMPRESSIONS["BITFIELDS"]:
  182. SUPPORTED: dict[int, list[tuple[int, ...]]] = {
  183. 32: [
  184. (0xFF0000, 0xFF00, 0xFF, 0x0),
  185. (0xFF000000, 0xFF0000, 0xFF00, 0x0),
  186. (0xFF000000, 0xFF00, 0xFF, 0x0),
  187. (0xFF000000, 0xFF0000, 0xFF00, 0xFF),
  188. (0xFF, 0xFF00, 0xFF0000, 0xFF000000),
  189. (0xFF0000, 0xFF00, 0xFF, 0xFF000000),
  190. (0xFF000000, 0xFF00, 0xFF, 0xFF0000),
  191. (0x0, 0x0, 0x0, 0x0),
  192. ],
  193. 24: [(0xFF0000, 0xFF00, 0xFF)],
  194. 16: [(0xF800, 0x7E0, 0x1F), (0x7C00, 0x3E0, 0x1F)],
  195. }
  196. MASK_MODES = {
  197. (32, (0xFF0000, 0xFF00, 0xFF, 0x0)): "BGRX",
  198. (32, (0xFF000000, 0xFF0000, 0xFF00, 0x0)): "XBGR",
  199. (32, (0xFF000000, 0xFF00, 0xFF, 0x0)): "BGXR",
  200. (32, (0xFF000000, 0xFF0000, 0xFF00, 0xFF)): "ABGR",
  201. (32, (0xFF, 0xFF00, 0xFF0000, 0xFF000000)): "RGBA",
  202. (32, (0xFF0000, 0xFF00, 0xFF, 0xFF000000)): "BGRA",
  203. (32, (0xFF000000, 0xFF00, 0xFF, 0xFF0000)): "BGAR",
  204. (32, (0x0, 0x0, 0x0, 0x0)): "BGRA",
  205. (24, (0xFF0000, 0xFF00, 0xFF)): "BGR",
  206. (16, (0xF800, 0x7E0, 0x1F)): "BGR;16",
  207. (16, (0x7C00, 0x3E0, 0x1F)): "BGR;15",
  208. }
  209. if file_info["bits"] in SUPPORTED:
  210. if (
  211. file_info["bits"] == 32
  212. and file_info["rgba_mask"] in SUPPORTED[file_info["bits"]]
  213. ):
  214. assert isinstance(file_info["rgba_mask"], tuple)
  215. raw_mode = MASK_MODES[(file_info["bits"], file_info["rgba_mask"])]
  216. self._mode = "RGBA" if "A" in raw_mode else self.mode
  217. elif (
  218. file_info["bits"] in (24, 16)
  219. and file_info["rgb_mask"] in SUPPORTED[file_info["bits"]]
  220. ):
  221. assert isinstance(file_info["rgb_mask"], tuple)
  222. raw_mode = MASK_MODES[(file_info["bits"], file_info["rgb_mask"])]
  223. else:
  224. msg = "Unsupported BMP bitfields layout"
  225. raise OSError(msg)
  226. else:
  227. msg = "Unsupported BMP bitfields layout"
  228. raise OSError(msg)
  229. elif file_info["compression"] == self.COMPRESSIONS["RAW"]:
  230. if file_info["bits"] == 32 and (
  231. header == 22 or USE_RAW_ALPHA # 32-bit .cur offset
  232. ):
  233. raw_mode, self._mode = "BGRA", "RGBA"
  234. elif file_info["compression"] in (
  235. self.COMPRESSIONS["RLE8"],
  236. self.COMPRESSIONS["RLE4"],
  237. ):
  238. decoder_name = "bmp_rle"
  239. else:
  240. msg = f"Unsupported BMP compression ({file_info['compression']})"
  241. raise OSError(msg)
  242. # --------------- Once the header is processed, process the palette/LUT
  243. if self.mode == "P": # Paletted for 1, 4 and 8 bit images
  244. # ---------------------------------------------------- 1-bit images
  245. if not (0 < file_info["colors"] <= 65536):
  246. msg = f"Unsupported BMP Palette size ({file_info['colors']})"
  247. raise OSError(msg)
  248. else:
  249. padding = file_info["palette_padding"]
  250. palette = read(padding * file_info["colors"])
  251. grayscale = True
  252. indices = (
  253. (0, 255)
  254. if file_info["colors"] == 2
  255. else list(range(file_info["colors"]))
  256. )
  257. # ----------------- Check if grayscale and ignore palette if so
  258. for ind, val in enumerate(indices):
  259. rgb = palette[ind * padding : ind * padding + 3]
  260. if rgb != o8(val) * 3:
  261. grayscale = False
  262. # ------- If all colors are gray, white or black, ditch palette
  263. if grayscale:
  264. self._mode = "1" if file_info["colors"] <= 2 else "L"
  265. raw_mode = self.mode
  266. else:
  267. self._mode = "P"
  268. self.palette = ImagePalette.raw(
  269. "BGRX" if padding == 4 else "BGR", palette
  270. )
  271. # ---------------------------- Finally set the tile data for the plugin
  272. self.info["compression"] = file_info["compression"]
  273. args: list[Any] = [raw_mode]
  274. if decoder_name == "bmp_rle":
  275. args.append(file_info["compression"] == self.COMPRESSIONS["RLE4"])
  276. else:
  277. assert isinstance(file_info["width"], int)
  278. args.append(((file_info["width"] * file_info["bits"] + 31) >> 3) & (~3))
  279. args.append(file_info["direction"])
  280. self.tile = [
  281. ImageFile._Tile(
  282. decoder_name,
  283. (0, 0, file_info["width"], file_info["height"]),
  284. offset or self.fp.tell(),
  285. tuple(args),
  286. )
  287. ]
  288. def _open(self) -> None:
  289. """Open file, check magic number and read header"""
  290. # read 14 bytes: magic number, filesize, reserved, header final offset
  291. assert self.fp is not None
  292. head_data = self.fp.read(14)
  293. # choke if the file does not have the required magic bytes
  294. if not _accept(head_data):
  295. msg = "Not a BMP file"
  296. raise SyntaxError(msg)
  297. # read the start position of the BMP image data (u32)
  298. offset = i32(head_data, 10)
  299. # load bitmap information (offset=raster info)
  300. self._bitmap(offset=offset)
  301. class BmpRleDecoder(ImageFile.PyDecoder):
  302. _pulls_fd = True
  303. def decode(self, buffer: Image.DecoderInput) -> tuple[int, int]:
  304. assert self.fd is not None
  305. rle4 = self.args[1]
  306. data = bytearray()
  307. x = 0
  308. dest_length = self.state.xsize * self.state.ysize
  309. while len(data) < dest_length:
  310. pixels = self.fd.read(1)
  311. byte = self.fd.read(1)
  312. if not pixels or not byte:
  313. break
  314. num_pixels = pixels[0]
  315. if num_pixels:
  316. # encoded mode
  317. if x + num_pixels > self.state.xsize:
  318. # Too much data for row
  319. num_pixels = max(0, self.state.xsize - x)
  320. if rle4:
  321. first_pixel = o8(byte[0] >> 4)
  322. second_pixel = o8(byte[0] & 0x0F)
  323. for index in range(num_pixels):
  324. if index % 2 == 0:
  325. data += first_pixel
  326. else:
  327. data += second_pixel
  328. else:
  329. data += byte * num_pixels
  330. x += num_pixels
  331. else:
  332. if byte[0] == 0:
  333. # end of line
  334. while len(data) % self.state.xsize != 0:
  335. data += b"\x00"
  336. x = 0
  337. elif byte[0] == 1:
  338. # end of bitmap
  339. break
  340. elif byte[0] == 2:
  341. # delta
  342. bytes_read = self.fd.read(2)
  343. if len(bytes_read) < 2:
  344. break
  345. right, up = bytes_read
  346. data += b"\x00" * min(
  347. dest_length - len(data), right + up * self.state.xsize
  348. )
  349. x = len(data) % self.state.xsize
  350. else:
  351. # absolute mode
  352. data_count = min(dest_length - len(data), byte[0])
  353. if rle4:
  354. # 2 pixels per byte, padded up to a whole byte
  355. byte_count = (data_count + 1) // 2
  356. bytes_read = self.fd.read(byte_count)
  357. for i, byte_read in enumerate(bytes_read):
  358. data += o8(byte_read >> 4)
  359. if i * 2 + 1 < data_count:
  360. data += o8(byte_read & 0x0F)
  361. else:
  362. byte_count = data_count
  363. bytes_read = self.fd.read(byte_count)
  364. data += bytes_read
  365. if len(bytes_read) < byte_count or len(data) == dest_length:
  366. break
  367. x += byte[0]
  368. # align to 16-bit word boundary
  369. if self.fd.tell() % 2 != 0:
  370. self.fd.seek(1, os.SEEK_CUR)
  371. rawmode = "L" if self.mode in {"1", "L"} else "P"
  372. self.set_as_raw(bytes(data), rawmode, (0, self.args[-1]))
  373. return -1, 0
  374. # =============================================================================
  375. # Image plugin for the DIB format (BMP alias)
  376. # =============================================================================
  377. class DibImageFile(BmpImageFile):
  378. format = "DIB"
  379. format_description = "Windows Bitmap"
  380. def _open(self) -> None:
  381. self._bitmap()
  382. #
  383. # --------------------------------------------------------------------
  384. # Write BMP file
  385. SAVE = {
  386. "1": ("1", 1, 2),
  387. "L": ("L", 8, 256),
  388. "P": ("P", 8, 256),
  389. "RGB": ("BGR", 24, 0),
  390. "RGBA": ("BGRA", 32, 0),
  391. }
  392. def _dib_save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
  393. _save(im, fp, filename, False)
  394. def _save(
  395. im: Image.Image, fp: IO[bytes], filename: str | bytes, bitmap_header: bool = True
  396. ) -> None:
  397. try:
  398. rawmode, bits, colors = SAVE[im.mode]
  399. except KeyError as e:
  400. msg = f"cannot write mode {im.mode} as BMP"
  401. raise OSError(msg) from e
  402. info = im.encoderinfo
  403. dpi = info.get("dpi", (96, 96))
  404. # 1 meter == 39.3701 inches
  405. ppm = tuple(int(x * 39.3701 + 0.5) for x in dpi)
  406. stride = ((im.size[0] * bits + 7) // 8 + 3) & (~3)
  407. header = 40 # or 64 for OS/2 version 2
  408. image = stride * im.size[1]
  409. if im.mode == "1":
  410. palette = b"".join(o8(i) * 3 + b"\x00" for i in (0, 255))
  411. elif im.mode == "L":
  412. palette = b"".join(o8(i) * 3 + b"\x00" for i in range(256))
  413. elif im.mode == "P":
  414. # Colors used should not be zero, as that is treated as the maximum
  415. palette = im.im.getpalette("RGB", "BGRX") or b"\x00\x00\x00\x00"
  416. colors = len(palette) // 4
  417. else:
  418. palette = None
  419. # bitmap header
  420. if bitmap_header:
  421. offset = 14 + header + colors * 4
  422. file_size = offset + image
  423. if file_size > 2**32 - 1:
  424. msg = "File size is too large for the BMP format"
  425. raise ValueError(msg)
  426. fp.write(
  427. b"BM" # file type (magic)
  428. + o32(file_size) # file size
  429. + o32(0) # reserved
  430. + o32(offset) # image data offset
  431. )
  432. # bitmap info header
  433. fp.write(
  434. o32(header) # info header size
  435. + o32(im.size[0]) # width
  436. + o32(im.size[1]) # height
  437. + o16(1) # planes
  438. + o16(bits) # depth
  439. + o32(0) # compression (0=uncompressed)
  440. + o32(image) # size of bitmap
  441. + o32(ppm[0]) # resolution
  442. + o32(ppm[1]) # resolution
  443. + o32(colors) # colors used
  444. + o32(colors) # colors important
  445. )
  446. fp.write(b"\0" * (header - 40)) # padding (for OS/2 format)
  447. if palette:
  448. fp.write(palette)
  449. ImageFile._save(
  450. im, fp, [ImageFile._Tile("raw", (0, 0, *im.size), 0, (rawmode, stride, -1))]
  451. )
  452. #
  453. # --------------------------------------------------------------------
  454. # Registry
  455. Image.register_open(BmpImageFile.format, BmpImageFile, _accept)
  456. Image.register_save(BmpImageFile.format, _save)
  457. Image.register_extension(BmpImageFile.format, ".bmp")
  458. Image.register_mime(BmpImageFile.format, "image/bmp")
  459. Image.register_decoder("bmp_rle", BmpRleDecoder)
  460. Image.register_open(DibImageFile.format, DibImageFile, _dib_accept)
  461. Image.register_save(DibImageFile.format, _dib_save)
  462. Image.register_extension(DibImageFile.format, ".dib")
  463. Image.register_mime(DibImageFile.format, "image/bmp")