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