BmpImagePlugin.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  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. raise OSError(f"Unsupported BMP header type ({file_info['header_size']})")
  133. # ------------------ Special case : header is reported 40, which
  134. # ---------------------- is shorter than real size for bpp >= 16
  135. self._size = file_info["width"], file_info["height"]
  136. # ------- If color count was not found in the header, compute from bits
  137. file_info["colors"] = (
  138. file_info["colors"]
  139. if file_info.get("colors", 0)
  140. else (1 << file_info["bits"])
  141. )
  142. if offset == 14 + file_info["header_size"] and file_info["bits"] <= 8:
  143. offset += 4 * file_info["colors"]
  144. # ---------------------- Check bit depth for unusual unsupported values
  145. self.mode, raw_mode = BIT2MODE.get(file_info["bits"], (None, None))
  146. if self.mode is None:
  147. raise OSError(f"Unsupported BMP pixel depth ({file_info['bits']})")
  148. # ---------------- Process BMP with Bitfields compression (not palette)
  149. decoder_name = "raw"
  150. if file_info["compression"] == self.BITFIELDS:
  151. SUPPORTED = {
  152. 32: [
  153. (0xFF0000, 0xFF00, 0xFF, 0x0),
  154. (0xFF0000, 0xFF00, 0xFF, 0xFF000000),
  155. (0xFF, 0xFF00, 0xFF0000, 0xFF000000),
  156. (0x0, 0x0, 0x0, 0x0),
  157. (0xFF000000, 0xFF0000, 0xFF00, 0x0),
  158. ],
  159. 24: [(0xFF0000, 0xFF00, 0xFF)],
  160. 16: [(0xF800, 0x7E0, 0x1F), (0x7C00, 0x3E0, 0x1F)],
  161. }
  162. MASK_MODES = {
  163. (32, (0xFF0000, 0xFF00, 0xFF, 0x0)): "BGRX",
  164. (32, (0xFF000000, 0xFF0000, 0xFF00, 0x0)): "XBGR",
  165. (32, (0xFF, 0xFF00, 0xFF0000, 0xFF000000)): "RGBA",
  166. (32, (0xFF0000, 0xFF00, 0xFF, 0xFF000000)): "BGRA",
  167. (32, (0x0, 0x0, 0x0, 0x0)): "BGRA",
  168. (24, (0xFF0000, 0xFF00, 0xFF)): "BGR",
  169. (16, (0xF800, 0x7E0, 0x1F)): "BGR;16",
  170. (16, (0x7C00, 0x3E0, 0x1F)): "BGR;15",
  171. }
  172. if file_info["bits"] in SUPPORTED:
  173. if (
  174. file_info["bits"] == 32
  175. and file_info["rgba_mask"] in SUPPORTED[file_info["bits"]]
  176. ):
  177. raw_mode = MASK_MODES[(file_info["bits"], file_info["rgba_mask"])]
  178. self.mode = "RGBA" if "A" in raw_mode else self.mode
  179. elif (
  180. file_info["bits"] in (24, 16)
  181. and file_info["rgb_mask"] in SUPPORTED[file_info["bits"]]
  182. ):
  183. raw_mode = MASK_MODES[(file_info["bits"], file_info["rgb_mask"])]
  184. else:
  185. raise OSError("Unsupported BMP bitfields layout")
  186. else:
  187. raise OSError("Unsupported BMP bitfields layout")
  188. elif file_info["compression"] == self.RAW:
  189. if file_info["bits"] == 32 and header == 22: # 32-bit .cur offset
  190. raw_mode, self.mode = "BGRA", "RGBA"
  191. elif file_info["compression"] == self.RLE8:
  192. decoder_name = "bmp_rle"
  193. else:
  194. raise OSError(f"Unsupported BMP compression ({file_info['compression']})")
  195. # --------------- Once the header is processed, process the palette/LUT
  196. if self.mode == "P": # Paletted for 1, 4 and 8 bit images
  197. # ---------------------------------------------------- 1-bit images
  198. if not (0 < file_info["colors"] <= 65536):
  199. raise OSError(f"Unsupported BMP Palette size ({file_info['colors']})")
  200. else:
  201. padding = file_info["palette_padding"]
  202. palette = read(padding * file_info["colors"])
  203. greyscale = True
  204. indices = (
  205. (0, 255)
  206. if file_info["colors"] == 2
  207. else list(range(file_info["colors"]))
  208. )
  209. # ----------------- Check if greyscale and ignore palette if so
  210. for ind, val in enumerate(indices):
  211. rgb = palette[ind * padding : ind * padding + 3]
  212. if rgb != o8(val) * 3:
  213. greyscale = False
  214. # ------- If all colors are grey, white or black, ditch palette
  215. if greyscale:
  216. self.mode = "1" if file_info["colors"] == 2 else "L"
  217. raw_mode = self.mode
  218. else:
  219. self.mode = "P"
  220. self.palette = ImagePalette.raw(
  221. "BGRX" if padding == 4 else "BGR", palette
  222. )
  223. # ---------------------------- Finally set the tile data for the plugin
  224. self.info["compression"] = file_info["compression"]
  225. self.tile = [
  226. (
  227. decoder_name,
  228. (0, 0, file_info["width"], file_info["height"]),
  229. offset or self.fp.tell(),
  230. (
  231. raw_mode,
  232. ((file_info["width"] * file_info["bits"] + 31) >> 3) & (~3),
  233. file_info["direction"],
  234. ),
  235. )
  236. ]
  237. def _open(self):
  238. """Open file, check magic number and read header"""
  239. # read 14 bytes: magic number, filesize, reserved, header final offset
  240. head_data = self.fp.read(14)
  241. # choke if the file does not have the required magic bytes
  242. if not _accept(head_data):
  243. raise SyntaxError("Not a BMP file")
  244. # read the start position of the BMP image data (u32)
  245. offset = i32(head_data, 10)
  246. # load bitmap information (offset=raster info)
  247. self._bitmap(offset=offset)
  248. class BmpRleDecoder(ImageFile.PyDecoder):
  249. _pulls_fd = True
  250. def decode(self, buffer):
  251. data = bytearray()
  252. x = 0
  253. while len(data) < self.state.xsize * self.state.ysize:
  254. pixels = self.fd.read(1)
  255. byte = self.fd.read(1)
  256. if not pixels or not byte:
  257. break
  258. num_pixels = pixels[0]
  259. if num_pixels:
  260. # encoded mode
  261. if x + num_pixels > self.state.xsize:
  262. # Too much data for row
  263. num_pixels = max(0, self.state.xsize - x)
  264. data += byte * num_pixels
  265. x += num_pixels
  266. else:
  267. if byte[0] == 0:
  268. # end of line
  269. while len(data) % self.state.xsize != 0:
  270. data += b"\x00"
  271. x = 0
  272. elif byte[0] == 1:
  273. # end of bitmap
  274. break
  275. elif byte[0] == 2:
  276. # delta
  277. bytes_read = self.fd.read(2)
  278. if len(bytes_read) < 2:
  279. break
  280. right, up = self.fd.read(2)
  281. data += b"\x00" * (right + up * self.state.xsize)
  282. x = len(data) % self.state.xsize
  283. else:
  284. # absolute mode
  285. bytes_read = self.fd.read(byte[0])
  286. data += bytes_read
  287. if len(bytes_read) < byte[0]:
  288. break
  289. x += byte[0]
  290. # align to 16-bit word boundary
  291. if self.fd.tell() % 2 != 0:
  292. self.fd.seek(1, os.SEEK_CUR)
  293. rawmode = "L" if self.mode == "L" else "P"
  294. self.set_as_raw(bytes(data), (rawmode, 0, self.args[-1]))
  295. return -1, 0
  296. # =============================================================================
  297. # Image plugin for the DIB format (BMP alias)
  298. # =============================================================================
  299. class DibImageFile(BmpImageFile):
  300. format = "DIB"
  301. format_description = "Windows Bitmap"
  302. def _open(self):
  303. self._bitmap()
  304. #
  305. # --------------------------------------------------------------------
  306. # Write BMP file
  307. SAVE = {
  308. "1": ("1", 1, 2),
  309. "L": ("L", 8, 256),
  310. "P": ("P", 8, 256),
  311. "RGB": ("BGR", 24, 0),
  312. "RGBA": ("BGRA", 32, 0),
  313. }
  314. def _dib_save(im, fp, filename):
  315. _save(im, fp, filename, False)
  316. def _save(im, fp, filename, bitmap_header=True):
  317. try:
  318. rawmode, bits, colors = SAVE[im.mode]
  319. except KeyError as e:
  320. raise OSError(f"cannot write mode {im.mode} as BMP") from e
  321. info = im.encoderinfo
  322. dpi = info.get("dpi", (96, 96))
  323. # 1 meter == 39.3701 inches
  324. ppm = tuple(map(lambda x: int(x * 39.3701 + 0.5), dpi))
  325. stride = ((im.size[0] * bits + 7) // 8 + 3) & (~3)
  326. header = 40 # or 64 for OS/2 version 2
  327. image = stride * im.size[1]
  328. # bitmap header
  329. if bitmap_header:
  330. offset = 14 + header + colors * 4
  331. file_size = offset + image
  332. if file_size > 2**32 - 1:
  333. raise ValueError("File size is too large for the BMP format")
  334. fp.write(
  335. b"BM" # file type (magic)
  336. + o32(file_size) # file size
  337. + o32(0) # reserved
  338. + o32(offset) # image data offset
  339. )
  340. # bitmap info header
  341. fp.write(
  342. o32(header) # info header size
  343. + o32(im.size[0]) # width
  344. + o32(im.size[1]) # height
  345. + o16(1) # planes
  346. + o16(bits) # depth
  347. + o32(0) # compression (0=uncompressed)
  348. + o32(image) # size of bitmap
  349. + o32(ppm[0]) # resolution
  350. + o32(ppm[1]) # resolution
  351. + o32(colors) # colors used
  352. + o32(colors) # colors important
  353. )
  354. fp.write(b"\0" * (header - 40)) # padding (for OS/2 format)
  355. if im.mode == "1":
  356. for i in (0, 255):
  357. fp.write(o8(i) * 4)
  358. elif im.mode == "L":
  359. for i in range(256):
  360. fp.write(o8(i) * 4)
  361. elif im.mode == "P":
  362. fp.write(im.im.getpalette("RGB", "BGRX"))
  363. ImageFile._save(im, fp, [("raw", (0, 0) + im.size, 0, (rawmode, stride, -1))])
  364. #
  365. # --------------------------------------------------------------------
  366. # Registry
  367. Image.register_open(BmpImageFile.format, BmpImageFile, _accept)
  368. Image.register_save(BmpImageFile.format, _save)
  369. Image.register_extension(BmpImageFile.format, ".bmp")
  370. Image.register_mime(BmpImageFile.format, "image/bmp")
  371. Image.register_decoder("bmp_rle", BmpRleDecoder)
  372. Image.register_open(DibImageFile.format, DibImageFile, _dib_accept)
  373. Image.register_save(DibImageFile.format, _dib_save)
  374. Image.register_extension(DibImageFile.format, ".dib")
  375. Image.register_mime(DibImageFile.format, "image/bmp")