BmpImagePlugin.py 18 KB

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