BmpImagePlugin.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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 . import Image, ImageFile, ImagePalette
  26. from ._binary import i8
  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[:4]) 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. file_info = {}
  66. # read bmp header size @offset 14 (this is part of the header size)
  67. file_info["header_size"] = i32(read(4))
  68. file_info["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. # -------------------------------------------------- IBM OS/2 Bitmap v1
  73. # ----- This format has different offsets because of width/height types
  74. if file_info["header_size"] == 12:
  75. file_info["width"] = i16(header_data[0:2])
  76. file_info["height"] = i16(header_data[2:4])
  77. file_info["planes"] = i16(header_data[4:6])
  78. file_info["bits"] = i16(header_data[6:8])
  79. file_info["compression"] = self.RAW
  80. file_info["palette_padding"] = 3
  81. # --------------------------------------------- Windows Bitmap v2 to v5
  82. # v3, OS/2 v2, v4, v5
  83. elif file_info["header_size"] in (40, 64, 108, 124):
  84. file_info["y_flip"] = i8(header_data[7]) == 0xFF
  85. file_info["direction"] = 1 if file_info["y_flip"] else -1
  86. file_info["width"] = i32(header_data[0:4])
  87. file_info["height"] = (
  88. i32(header_data[4:8])
  89. if not file_info["y_flip"]
  90. else 2 ** 32 - i32(header_data[4:8])
  91. )
  92. file_info["planes"] = i16(header_data[8:10])
  93. file_info["bits"] = i16(header_data[10:12])
  94. file_info["compression"] = i32(header_data[12:16])
  95. # byte size of pixel data
  96. file_info["data_size"] = i32(header_data[16:20])
  97. file_info["pixels_per_meter"] = (
  98. i32(header_data[20:24]),
  99. i32(header_data[24:28]),
  100. )
  101. file_info["colors"] = i32(header_data[28:32])
  102. file_info["palette_padding"] = 4
  103. self.info["dpi"] = tuple(
  104. int(x / 39.3701 + 0.5) for x in file_info["pixels_per_meter"]
  105. )
  106. if file_info["compression"] == self.BITFIELDS:
  107. if len(header_data) >= 52:
  108. for idx, mask in enumerate(
  109. ["r_mask", "g_mask", "b_mask", "a_mask"]
  110. ):
  111. file_info[mask] = i32(header_data[36 + idx * 4 : 40 + idx * 4])
  112. else:
  113. # 40 byte headers only have the three components in the
  114. # bitfields masks, ref:
  115. # https://msdn.microsoft.com/en-us/library/windows/desktop/dd183376(v=vs.85).aspx
  116. # See also
  117. # https://github.com/python-pillow/Pillow/issues/1293
  118. # There is a 4th component in the RGBQuad, in the alpha
  119. # location, but it is listed as a reserved component,
  120. # and it is not generally an alpha channel
  121. file_info["a_mask"] = 0x0
  122. for mask in ["r_mask", "g_mask", "b_mask"]:
  123. file_info[mask] = i32(read(4))
  124. file_info["rgb_mask"] = (
  125. file_info["r_mask"],
  126. file_info["g_mask"],
  127. file_info["b_mask"],
  128. )
  129. file_info["rgba_mask"] = (
  130. file_info["r_mask"],
  131. file_info["g_mask"],
  132. file_info["b_mask"],
  133. file_info["a_mask"],
  134. )
  135. else:
  136. raise OSError(f"Unsupported BMP header type ({file_info['header_size']})")
  137. # ------------------ Special case : header is reported 40, which
  138. # ---------------------- is shorter than real size for bpp >= 16
  139. self._size = file_info["width"], file_info["height"]
  140. # ------- If color count was not found in the header, compute from bits
  141. file_info["colors"] = (
  142. file_info["colors"]
  143. if file_info.get("colors", 0)
  144. else (1 << file_info["bits"])
  145. )
  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. raise OSError(f"Unsupported BMP pixel depth ({file_info['bits']})")
  150. # ---------------- Process BMP with Bitfields compression (not palette)
  151. if file_info["compression"] == self.BITFIELDS:
  152. SUPPORTED = {
  153. 32: [
  154. (0xFF0000, 0xFF00, 0xFF, 0x0),
  155. (0xFF0000, 0xFF00, 0xFF, 0xFF000000),
  156. (0xFF, 0xFF00, 0xFF0000, 0xFF000000),
  157. (0x0, 0x0, 0x0, 0x0),
  158. (0xFF000000, 0xFF0000, 0xFF00, 0x0),
  159. ],
  160. 24: [(0xFF0000, 0xFF00, 0xFF)],
  161. 16: [(0xF800, 0x7E0, 0x1F), (0x7C00, 0x3E0, 0x1F)],
  162. }
  163. MASK_MODES = {
  164. (32, (0xFF0000, 0xFF00, 0xFF, 0x0)): "BGRX",
  165. (32, (0xFF000000, 0xFF0000, 0xFF00, 0x0)): "XBGR",
  166. (32, (0xFF, 0xFF00, 0xFF0000, 0xFF000000)): "RGBA",
  167. (32, (0xFF0000, 0xFF00, 0xFF, 0xFF000000)): "BGRA",
  168. (32, (0x0, 0x0, 0x0, 0x0)): "BGRA",
  169. (24, (0xFF0000, 0xFF00, 0xFF)): "BGR",
  170. (16, (0xF800, 0x7E0, 0x1F)): "BGR;16",
  171. (16, (0x7C00, 0x3E0, 0x1F)): "BGR;15",
  172. }
  173. if file_info["bits"] in SUPPORTED:
  174. if (
  175. file_info["bits"] == 32
  176. and file_info["rgba_mask"] in SUPPORTED[file_info["bits"]]
  177. ):
  178. raw_mode = MASK_MODES[(file_info["bits"], file_info["rgba_mask"])]
  179. self.mode = "RGBA" if "A" in raw_mode else self.mode
  180. elif (
  181. file_info["bits"] in (24, 16)
  182. and file_info["rgb_mask"] in SUPPORTED[file_info["bits"]]
  183. ):
  184. raw_mode = MASK_MODES[(file_info["bits"], file_info["rgb_mask"])]
  185. else:
  186. raise OSError("Unsupported BMP bitfields layout")
  187. else:
  188. raise OSError("Unsupported BMP bitfields layout")
  189. elif file_info["compression"] == self.RAW:
  190. if file_info["bits"] == 32 and header == 22: # 32-bit .cur offset
  191. raw_mode, self.mode = "BGRA", "RGBA"
  192. else:
  193. raise OSError(f"Unsupported BMP compression ({file_info['compression']})")
  194. # --------------- Once the header is processed, process the palette/LUT
  195. if self.mode == "P": # Paletted for 1, 4 and 8 bit images
  196. # ---------------------------------------------------- 1-bit images
  197. if not (0 < file_info["colors"] <= 65536):
  198. raise OSError(f"Unsupported BMP Palette size ({file_info['colors']})")
  199. else:
  200. padding = file_info["palette_padding"]
  201. palette = read(padding * file_info["colors"])
  202. greyscale = True
  203. indices = (
  204. (0, 255)
  205. if file_info["colors"] == 2
  206. else list(range(file_info["colors"]))
  207. )
  208. # ----------------- Check if greyscale and ignore palette if so
  209. for ind, val in enumerate(indices):
  210. rgb = palette[ind * padding : ind * padding + 3]
  211. if rgb != o8(val) * 3:
  212. greyscale = False
  213. # ------- If all colors are grey, white or black, ditch palette
  214. if greyscale:
  215. self.mode = "1" if file_info["colors"] == 2 else "L"
  216. raw_mode = self.mode
  217. else:
  218. self.mode = "P"
  219. self.palette = ImagePalette.raw(
  220. "BGRX" if padding == 4 else "BGR", palette
  221. )
  222. # ---------------------------- Finally set the tile data for the plugin
  223. self.info["compression"] = file_info["compression"]
  224. self.tile = [
  225. (
  226. "raw",
  227. (0, 0, file_info["width"], file_info["height"]),
  228. offset or self.fp.tell(),
  229. (
  230. raw_mode,
  231. ((file_info["width"] * file_info["bits"] + 31) >> 3) & (~3),
  232. file_info["direction"],
  233. ),
  234. )
  235. ]
  236. def _open(self):
  237. """ Open file, check magic number and read header """
  238. # read 14 bytes: magic number, filesize, reserved, header final offset
  239. head_data = self.fp.read(14)
  240. # choke if the file does not have the required magic bytes
  241. if not _accept(head_data):
  242. raise SyntaxError("Not a BMP file")
  243. # read the start position of the BMP image data (u32)
  244. offset = i32(head_data[10:14])
  245. # load bitmap information (offset=raster info)
  246. self._bitmap(offset=offset)
  247. # =============================================================================
  248. # Image plugin for the DIB format (BMP alias)
  249. # =============================================================================
  250. class DibImageFile(BmpImageFile):
  251. format = "DIB"
  252. format_description = "Windows Bitmap"
  253. def _open(self):
  254. self._bitmap()
  255. #
  256. # --------------------------------------------------------------------
  257. # Write BMP file
  258. SAVE = {
  259. "1": ("1", 1, 2),
  260. "L": ("L", 8, 256),
  261. "P": ("P", 8, 256),
  262. "RGB": ("BGR", 24, 0),
  263. "RGBA": ("BGRA", 32, 0),
  264. }
  265. def _dib_save(im, fp, filename):
  266. _save(im, fp, filename, False)
  267. def _save(im, fp, filename, bitmap_header=True):
  268. try:
  269. rawmode, bits, colors = SAVE[im.mode]
  270. except KeyError as e:
  271. raise OSError(f"cannot write mode {im.mode} as BMP") from e
  272. info = im.encoderinfo
  273. dpi = info.get("dpi", (96, 96))
  274. # 1 meter == 39.3701 inches
  275. ppm = tuple(map(lambda x: int(x * 39.3701 + 0.5), dpi))
  276. stride = ((im.size[0] * bits + 7) // 8 + 3) & (~3)
  277. header = 40 # or 64 for OS/2 version 2
  278. image = stride * im.size[1]
  279. # bitmap header
  280. if bitmap_header:
  281. offset = 14 + header + colors * 4
  282. file_size = offset + image
  283. if file_size > 2 ** 32 - 1:
  284. raise ValueError("File size is too large for the BMP format")
  285. fp.write(
  286. b"BM" # file type (magic)
  287. + o32(file_size) # file size
  288. + o32(0) # reserved
  289. + o32(offset) # image data offset
  290. )
  291. # bitmap info header
  292. fp.write(
  293. o32(header) # info header size
  294. + o32(im.size[0]) # width
  295. + o32(im.size[1]) # height
  296. + o16(1) # planes
  297. + o16(bits) # depth
  298. + o32(0) # compression (0=uncompressed)
  299. + o32(image) # size of bitmap
  300. + o32(ppm[0]) # resolution
  301. + o32(ppm[1]) # resolution
  302. + o32(colors) # colors used
  303. + o32(colors) # colors important
  304. )
  305. fp.write(b"\0" * (header - 40)) # padding (for OS/2 format)
  306. if im.mode == "1":
  307. for i in (0, 255):
  308. fp.write(o8(i) * 4)
  309. elif im.mode == "L":
  310. for i in range(256):
  311. fp.write(o8(i) * 4)
  312. elif im.mode == "P":
  313. fp.write(im.im.getpalette("RGB", "BGRX"))
  314. ImageFile._save(im, fp, [("raw", (0, 0) + im.size, 0, (rawmode, stride, -1))])
  315. #
  316. # --------------------------------------------------------------------
  317. # Registry
  318. Image.register_open(BmpImageFile.format, BmpImageFile, _accept)
  319. Image.register_save(BmpImageFile.format, _save)
  320. Image.register_extension(BmpImageFile.format, ".bmp")
  321. Image.register_mime(BmpImageFile.format, "image/bmp")
  322. Image.register_open(DibImageFile.format, DibImageFile, _dib_accept)
  323. Image.register_save(DibImageFile.format, _dib_save)
  324. Image.register_extension(DibImageFile.format, ".dib")
  325. Image.register_mime(DibImageFile.format, "image/bmp")