BmpImagePlugin.py 19 KB

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