BmpImagePlugin.py 19 KB

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