BmpImagePlugin.py 19 KB

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