BmpImagePlugin.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  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. if not file_info.get("colors", 0):
  164. file_info["colors"] = 1 << file_info["bits"]
  165. assert isinstance(file_info["palette_padding"], int)
  166. assert isinstance(file_info["colors"], int)
  167. if offset == 14 + file_info["header_size"] and file_info["bits"] <= 8:
  168. offset += file_info["palette_padding"] * 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 (
  226. header == 22 or USE_RAW_ALPHA # 32-bit .cur offset
  227. ):
  228. raw_mode, self._mode = "BGRA", "RGBA"
  229. elif file_info["compression"] in (
  230. self.COMPRESSIONS["RLE8"],
  231. self.COMPRESSIONS["RLE4"],
  232. ):
  233. decoder_name = "bmp_rle"
  234. else:
  235. msg = f"Unsupported BMP compression ({file_info['compression']})"
  236. raise OSError(msg)
  237. # --------------- Once the header is processed, process the palette/LUT
  238. if self.mode == "P": # Paletted for 1, 4 and 8 bit images
  239. # ---------------------------------------------------- 1-bit images
  240. if not (0 < file_info["colors"] <= 65536):
  241. msg = f"Unsupported BMP Palette size ({file_info['colors']})"
  242. raise OSError(msg)
  243. else:
  244. padding = file_info["palette_padding"]
  245. palette = read(padding * file_info["colors"])
  246. grayscale = True
  247. indices = (
  248. (0, 255)
  249. if file_info["colors"] == 2
  250. else list(range(file_info["colors"]))
  251. )
  252. # ----------------- Check if grayscale and ignore palette if so
  253. for ind, val in enumerate(indices):
  254. rgb = palette[ind * padding : ind * padding + 3]
  255. if rgb != o8(val) * 3:
  256. grayscale = False
  257. # ------- If all colors are gray, white or black, ditch palette
  258. if grayscale:
  259. self._mode = "1" if file_info["colors"] == 2 else "L"
  260. raw_mode = self.mode
  261. else:
  262. self._mode = "P"
  263. self.palette = ImagePalette.raw(
  264. "BGRX" if padding == 4 else "BGR", palette
  265. )
  266. # ---------------------------- Finally set the tile data for the plugin
  267. self.info["compression"] = file_info["compression"]
  268. args: list[Any] = [raw_mode]
  269. if decoder_name == "bmp_rle":
  270. args.append(file_info["compression"] == self.COMPRESSIONS["RLE4"])
  271. else:
  272. assert isinstance(file_info["width"], int)
  273. args.append(((file_info["width"] * file_info["bits"] + 31) >> 3) & (~3))
  274. args.append(file_info["direction"])
  275. self.tile = [
  276. ImageFile._Tile(
  277. decoder_name,
  278. (0, 0, file_info["width"], file_info["height"]),
  279. offset or self.fp.tell(),
  280. tuple(args),
  281. )
  282. ]
  283. def _open(self) -> None:
  284. """Open file, check magic number and read header"""
  285. # read 14 bytes: magic number, filesize, reserved, header final offset
  286. assert self.fp is not None
  287. head_data = self.fp.read(14)
  288. # choke if the file does not have the required magic bytes
  289. if not _accept(head_data):
  290. msg = "Not a BMP file"
  291. raise SyntaxError(msg)
  292. # read the start position of the BMP image data (u32)
  293. offset = i32(head_data, 10)
  294. # load bitmap information (offset=raster info)
  295. self._bitmap(offset=offset)
  296. class BmpRleDecoder(ImageFile.PyDecoder):
  297. _pulls_fd = True
  298. def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:
  299. assert self.fd is not None
  300. rle4 = self.args[1]
  301. data = bytearray()
  302. x = 0
  303. dest_length = self.state.xsize * self.state.ysize
  304. while len(data) < dest_length:
  305. pixels = self.fd.read(1)
  306. byte = self.fd.read(1)
  307. if not pixels or not byte:
  308. break
  309. num_pixels = pixels[0]
  310. if num_pixels:
  311. # encoded mode
  312. if x + num_pixels > self.state.xsize:
  313. # Too much data for row
  314. num_pixels = max(0, self.state.xsize - x)
  315. if rle4:
  316. first_pixel = o8(byte[0] >> 4)
  317. second_pixel = o8(byte[0] & 0x0F)
  318. for index in range(num_pixels):
  319. if index % 2 == 0:
  320. data += first_pixel
  321. else:
  322. data += second_pixel
  323. else:
  324. data += byte * num_pixels
  325. x += num_pixels
  326. else:
  327. if byte[0] == 0:
  328. # end of line
  329. while len(data) % self.state.xsize != 0:
  330. data += b"\x00"
  331. x = 0
  332. elif byte[0] == 1:
  333. # end of bitmap
  334. break
  335. elif byte[0] == 2:
  336. # delta
  337. bytes_read = self.fd.read(2)
  338. if len(bytes_read) < 2:
  339. break
  340. right, up = bytes_read
  341. data += b"\x00" * (right + up * self.state.xsize)
  342. x = len(data) % self.state.xsize
  343. else:
  344. # absolute mode
  345. if rle4:
  346. # 2 pixels per byte
  347. byte_count = byte[0] // 2
  348. bytes_read = self.fd.read(byte_count)
  349. for byte_read in bytes_read:
  350. data += o8(byte_read >> 4)
  351. data += o8(byte_read & 0x0F)
  352. else:
  353. byte_count = byte[0]
  354. bytes_read = self.fd.read(byte_count)
  355. data += bytes_read
  356. if len(bytes_read) < byte_count:
  357. break
  358. x += byte[0]
  359. # align to 16-bit word boundary
  360. if self.fd.tell() % 2 != 0:
  361. self.fd.seek(1, os.SEEK_CUR)
  362. rawmode = "L" if self.mode == "L" else "P"
  363. self.set_as_raw(bytes(data), rawmode, (0, self.args[-1]))
  364. return -1, 0
  365. # =============================================================================
  366. # Image plugin for the DIB format (BMP alias)
  367. # =============================================================================
  368. class DibImageFile(BmpImageFile):
  369. format = "DIB"
  370. format_description = "Windows Bitmap"
  371. def _open(self) -> None:
  372. self._bitmap()
  373. #
  374. # --------------------------------------------------------------------
  375. # Write BMP file
  376. SAVE = {
  377. "1": ("1", 1, 2),
  378. "L": ("L", 8, 256),
  379. "P": ("P", 8, 256),
  380. "RGB": ("BGR", 24, 0),
  381. "RGBA": ("BGRA", 32, 0),
  382. }
  383. def _dib_save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
  384. _save(im, fp, filename, False)
  385. def _save(
  386. im: Image.Image, fp: IO[bytes], filename: str | bytes, bitmap_header: bool = True
  387. ) -> None:
  388. try:
  389. rawmode, bits, colors = SAVE[im.mode]
  390. except KeyError as e:
  391. msg = f"cannot write mode {im.mode} as BMP"
  392. raise OSError(msg) from e
  393. info = im.encoderinfo
  394. dpi = info.get("dpi", (96, 96))
  395. # 1 meter == 39.3701 inches
  396. ppm = tuple(int(x * 39.3701 + 0.5) for x in dpi)
  397. stride = ((im.size[0] * bits + 7) // 8 + 3) & (~3)
  398. header = 40 # or 64 for OS/2 version 2
  399. image = stride * im.size[1]
  400. if im.mode == "1":
  401. palette = b"".join(o8(i) * 3 + b"\x00" for i in (0, 255))
  402. elif im.mode == "L":
  403. palette = b"".join(o8(i) * 3 + b"\x00" for i in range(256))
  404. elif im.mode == "P":
  405. palette = im.im.getpalette("RGB", "BGRX")
  406. colors = len(palette) // 4
  407. else:
  408. palette = None
  409. # bitmap header
  410. if bitmap_header:
  411. offset = 14 + header + colors * 4
  412. file_size = offset + image
  413. if file_size > 2**32 - 1:
  414. msg = "File size is too large for the BMP format"
  415. raise ValueError(msg)
  416. fp.write(
  417. b"BM" # file type (magic)
  418. + o32(file_size) # file size
  419. + o32(0) # reserved
  420. + o32(offset) # image data offset
  421. )
  422. # bitmap info header
  423. fp.write(
  424. o32(header) # info header size
  425. + o32(im.size[0]) # width
  426. + o32(im.size[1]) # height
  427. + o16(1) # planes
  428. + o16(bits) # depth
  429. + o32(0) # compression (0=uncompressed)
  430. + o32(image) # size of bitmap
  431. + o32(ppm[0]) # resolution
  432. + o32(ppm[1]) # resolution
  433. + o32(colors) # colors used
  434. + o32(colors) # colors important
  435. )
  436. fp.write(b"\0" * (header - 40)) # padding (for OS/2 format)
  437. if palette:
  438. fp.write(palette)
  439. ImageFile._save(
  440. im, fp, [ImageFile._Tile("raw", (0, 0) + im.size, 0, (rawmode, stride, -1))]
  441. )
  442. #
  443. # --------------------------------------------------------------------
  444. # Registry
  445. Image.register_open(BmpImageFile.format, BmpImageFile, _accept)
  446. Image.register_save(BmpImageFile.format, _save)
  447. Image.register_extension(BmpImageFile.format, ".bmp")
  448. Image.register_mime(BmpImageFile.format, "image/bmp")
  449. Image.register_decoder("bmp_rle", BmpRleDecoder)
  450. Image.register_open(DibImageFile.format, DibImageFile, _dib_accept)
  451. Image.register_save(DibImageFile.format, _dib_save)
  452. Image.register_extension(DibImageFile.format, ".dib")
  453. Image.register_mime(DibImageFile.format, "image/bmp")