BmpImagePlugin.py 17 KB

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