BmpImagePlugin.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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 i16le as i16
  27. from ._binary import i32le as i32
  28. from ._binary import o8
  29. from ._binary import o16le as o16
  30. from ._binary import o32le as o32
  31. #
  32. # --------------------------------------------------------------------
  33. # Read BMP file
  34. BIT2MODE = {
  35. # bits => mode, rawmode
  36. 1: ("P", "P;1"),
  37. 4: ("P", "P;4"),
  38. 8: ("P", "P"),
  39. 16: ("RGB", "BGR;15"),
  40. 24: ("RGB", "BGR"),
  41. 32: ("RGB", "BGRX"),
  42. }
  43. def _accept(prefix):
  44. return prefix[:2] == b"BM"
  45. def _dib_accept(prefix):
  46. return i32(prefix) in [12, 40, 64, 108, 124]
  47. # =============================================================================
  48. # Image plugin for the Windows BMP format.
  49. # =============================================================================
  50. class BmpImageFile(ImageFile.ImageFile):
  51. """ Image plugin for the Windows Bitmap format (BMP) """
  52. # ------------------------------------------------------------- Description
  53. format_description = "Windows Bitmap"
  54. format = "BMP"
  55. # -------------------------------------------------- BMP Compression values
  56. COMPRESSIONS = {"RAW": 0, "RLE8": 1, "RLE4": 2, "BITFIELDS": 3, "JPEG": 4, "PNG": 5}
  57. for k, v in COMPRESSIONS.items():
  58. vars()[k] = v
  59. def _bitmap(self, header=0, offset=0):
  60. """ Read relevant info about the BMP """
  61. read, seek = self.fp.read, self.fp.seek
  62. if header:
  63. seek(header)
  64. file_info = {}
  65. # read bmp header size @offset 14 (this is part of the header size)
  66. file_info["header_size"] = i32(read(4))
  67. file_info["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. raise OSError(f"Unsupported BMP header type ({file_info['header_size']})")
  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. # ---------------------- Check bit depth for unusual unsupported values
  144. self.mode, raw_mode = BIT2MODE.get(file_info["bits"], (None, None))
  145. if self.mode is None:
  146. raise OSError(f"Unsupported BMP pixel depth ({file_info['bits']})")
  147. # ---------------- Process BMP with Bitfields compression (not palette)
  148. if file_info["compression"] == self.BITFIELDS:
  149. SUPPORTED = {
  150. 32: [
  151. (0xFF0000, 0xFF00, 0xFF, 0x0),
  152. (0xFF0000, 0xFF00, 0xFF, 0xFF000000),
  153. (0xFF, 0xFF00, 0xFF0000, 0xFF000000),
  154. (0x0, 0x0, 0x0, 0x0),
  155. (0xFF000000, 0xFF0000, 0xFF00, 0x0),
  156. ],
  157. 24: [(0xFF0000, 0xFF00, 0xFF)],
  158. 16: [(0xF800, 0x7E0, 0x1F), (0x7C00, 0x3E0, 0x1F)],
  159. }
  160. MASK_MODES = {
  161. (32, (0xFF0000, 0xFF00, 0xFF, 0x0)): "BGRX",
  162. (32, (0xFF000000, 0xFF0000, 0xFF00, 0x0)): "XBGR",
  163. (32, (0xFF, 0xFF00, 0xFF0000, 0xFF000000)): "RGBA",
  164. (32, (0xFF0000, 0xFF00, 0xFF, 0xFF000000)): "BGRA",
  165. (32, (0x0, 0x0, 0x0, 0x0)): "BGRA",
  166. (24, (0xFF0000, 0xFF00, 0xFF)): "BGR",
  167. (16, (0xF800, 0x7E0, 0x1F)): "BGR;16",
  168. (16, (0x7C00, 0x3E0, 0x1F)): "BGR;15",
  169. }
  170. if file_info["bits"] in SUPPORTED:
  171. if (
  172. file_info["bits"] == 32
  173. and file_info["rgba_mask"] in SUPPORTED[file_info["bits"]]
  174. ):
  175. raw_mode = MASK_MODES[(file_info["bits"], file_info["rgba_mask"])]
  176. self.mode = "RGBA" if "A" in raw_mode else self.mode
  177. elif (
  178. file_info["bits"] in (24, 16)
  179. and file_info["rgb_mask"] in SUPPORTED[file_info["bits"]]
  180. ):
  181. raw_mode = MASK_MODES[(file_info["bits"], file_info["rgb_mask"])]
  182. else:
  183. raise OSError("Unsupported BMP bitfields layout")
  184. else:
  185. raise OSError("Unsupported BMP bitfields layout")
  186. elif file_info["compression"] == self.RAW:
  187. if file_info["bits"] == 32 and header == 22: # 32-bit .cur offset
  188. raw_mode, self.mode = "BGRA", "RGBA"
  189. else:
  190. raise OSError(f"Unsupported BMP compression ({file_info['compression']})")
  191. # --------------- Once the header is processed, process the palette/LUT
  192. if self.mode == "P": # Paletted for 1, 4 and 8 bit images
  193. # ---------------------------------------------------- 1-bit images
  194. if not (0 < file_info["colors"] <= 65536):
  195. raise OSError(f"Unsupported BMP Palette size ({file_info['colors']})")
  196. else:
  197. padding = file_info["palette_padding"]
  198. palette = read(padding * file_info["colors"])
  199. greyscale = True
  200. indices = (
  201. (0, 255)
  202. if file_info["colors"] == 2
  203. else list(range(file_info["colors"]))
  204. )
  205. # ----------------- Check if greyscale and ignore palette if so
  206. for ind, val in enumerate(indices):
  207. rgb = palette[ind * padding : ind * padding + 3]
  208. if rgb != o8(val) * 3:
  209. greyscale = False
  210. # ------- If all colors are grey, white or black, ditch palette
  211. if greyscale:
  212. self.mode = "1" if file_info["colors"] == 2 else "L"
  213. raw_mode = self.mode
  214. else:
  215. self.mode = "P"
  216. self.palette = ImagePalette.raw(
  217. "BGRX" if padding == 4 else "BGR", palette
  218. )
  219. # ---------------------------- Finally set the tile data for the plugin
  220. self.info["compression"] = file_info["compression"]
  221. self.tile = [
  222. (
  223. "raw",
  224. (0, 0, file_info["width"], file_info["height"]),
  225. offset or self.fp.tell(),
  226. (
  227. raw_mode,
  228. ((file_info["width"] * file_info["bits"] + 31) >> 3) & (~3),
  229. file_info["direction"],
  230. ),
  231. )
  232. ]
  233. def _open(self):
  234. """ Open file, check magic number and read header """
  235. # read 14 bytes: magic number, filesize, reserved, header final offset
  236. head_data = self.fp.read(14)
  237. # choke if the file does not have the required magic bytes
  238. if not _accept(head_data):
  239. raise SyntaxError("Not a BMP file")
  240. # read the start position of the BMP image data (u32)
  241. offset = i32(head_data, 10)
  242. # load bitmap information (offset=raster info)
  243. self._bitmap(offset=offset)
  244. # =============================================================================
  245. # Image plugin for the DIB format (BMP alias)
  246. # =============================================================================
  247. class DibImageFile(BmpImageFile):
  248. format = "DIB"
  249. format_description = "Windows Bitmap"
  250. def _open(self):
  251. self._bitmap()
  252. #
  253. # --------------------------------------------------------------------
  254. # Write BMP file
  255. SAVE = {
  256. "1": ("1", 1, 2),
  257. "L": ("L", 8, 256),
  258. "P": ("P", 8, 256),
  259. "RGB": ("BGR", 24, 0),
  260. "RGBA": ("BGRA", 32, 0),
  261. }
  262. def _dib_save(im, fp, filename):
  263. _save(im, fp, filename, False)
  264. def _save(im, fp, filename, bitmap_header=True):
  265. try:
  266. rawmode, bits, colors = SAVE[im.mode]
  267. except KeyError as e:
  268. raise OSError(f"cannot write mode {im.mode} as BMP") from e
  269. info = im.encoderinfo
  270. dpi = info.get("dpi", (96, 96))
  271. # 1 meter == 39.3701 inches
  272. ppm = tuple(map(lambda x: int(x * 39.3701 + 0.5), dpi))
  273. stride = ((im.size[0] * bits + 7) // 8 + 3) & (~3)
  274. header = 40 # or 64 for OS/2 version 2
  275. image = stride * im.size[1]
  276. # bitmap header
  277. if bitmap_header:
  278. offset = 14 + header + colors * 4
  279. file_size = offset + image
  280. if file_size > 2 ** 32 - 1:
  281. raise ValueError("File size is too large for the BMP format")
  282. fp.write(
  283. b"BM" # file type (magic)
  284. + o32(file_size) # file size
  285. + o32(0) # reserved
  286. + o32(offset) # image data offset
  287. )
  288. # bitmap info header
  289. fp.write(
  290. o32(header) # info header size
  291. + o32(im.size[0]) # width
  292. + o32(im.size[1]) # height
  293. + o16(1) # planes
  294. + o16(bits) # depth
  295. + o32(0) # compression (0=uncompressed)
  296. + o32(image) # size of bitmap
  297. + o32(ppm[0]) # resolution
  298. + o32(ppm[1]) # resolution
  299. + o32(colors) # colors used
  300. + o32(colors) # colors important
  301. )
  302. fp.write(b"\0" * (header - 40)) # padding (for OS/2 format)
  303. if im.mode == "1":
  304. for i in (0, 255):
  305. fp.write(o8(i) * 4)
  306. elif im.mode == "L":
  307. for i in range(256):
  308. fp.write(o8(i) * 4)
  309. elif im.mode == "P":
  310. fp.write(im.im.getpalette("RGB", "BGRX"))
  311. ImageFile._save(im, fp, [("raw", (0, 0) + im.size, 0, (rawmode, stride, -1))])
  312. #
  313. # --------------------------------------------------------------------
  314. # Registry
  315. Image.register_open(BmpImageFile.format, BmpImageFile, _accept)
  316. Image.register_save(BmpImageFile.format, _save)
  317. Image.register_extension(BmpImageFile.format, ".bmp")
  318. Image.register_mime(BmpImageFile.format, "image/bmp")
  319. Image.register_open(DibImageFile.format, DibImageFile, _dib_accept)
  320. Image.register_save(DibImageFile.format, _dib_save)
  321. Image.register_extension(DibImageFile.format, ".dib")
  322. Image.register_mime(DibImageFile.format, "image/bmp")