You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

BmpImagePlugin.py 14KB

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, i16le as i16, i32le as i32, o8, o16le as o16, o32le as o32
  27. # __version__ is deprecated and will be removed in a future version. Use
  28. # PIL.__version__ instead.
  29. __version__ = "0.7"
  30. #
  31. # --------------------------------------------------------------------
  32. # Read BMP file
  33. BIT2MODE = {
  34. # bits => mode, rawmode
  35. 1: ("P", "P;1"),
  36. 4: ("P", "P;4"),
  37. 8: ("P", "P"),
  38. 16: ("RGB", "BGR;15"),
  39. 24: ("RGB", "BGR"),
  40. 32: ("RGB", "BGRX"),
  41. }
  42. def _accept(prefix):
  43. return prefix[:2] == b"BM"
  44. def _dib_accept(prefix):
  45. return i32(prefix[:4]) in [12, 40, 64, 108, 124]
  46. # =============================================================================
  47. # Image plugin for the Windows BMP format.
  48. # =============================================================================
  49. class BmpImageFile(ImageFile.ImageFile):
  50. """ Image plugin for the Windows Bitmap format (BMP) """
  51. # ------------------------------------------------------------- Description
  52. format_description = "Windows Bitmap"
  53. format = "BMP"
  54. # -------------------------------------------------- BMP Compression values
  55. COMPRESSIONS = {"RAW": 0, "RLE8": 1, "RLE4": 2, "BITFIELDS": 3, "JPEG": 4, "PNG": 5}
  56. for k, v in COMPRESSIONS.items():
  57. vars()[k] = v
  58. def _bitmap(self, header=0, offset=0):
  59. """ Read relevant info about the BMP """
  60. read, seek = self.fp.read, self.fp.seek
  61. if header:
  62. seek(header)
  63. file_info = {}
  64. # read bmp header size @offset 14 (this is part of the header size)
  65. file_info["header_size"] = i32(read(4))
  66. file_info["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:2])
  74. file_info["height"] = i16(header_data[2:4])
  75. file_info["planes"] = i16(header_data[4:6])
  76. file_info["bits"] = i16(header_data[6:8])
  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"] = i8(header_data[7]) == 0xFF
  83. file_info["direction"] = 1 if file_info["y_flip"] else -1
  84. file_info["width"] = i32(header_data[0:4])
  85. file_info["height"] = (
  86. i32(header_data[4:8])
  87. if not file_info["y_flip"]
  88. else 2 ** 32 - i32(header_data[4:8])
  89. )
  90. file_info["planes"] = i16(header_data[8:10])
  91. file_info["bits"] = i16(header_data[10:12])
  92. file_info["compression"] = i32(header_data[12:16])
  93. # byte size of pixel data
  94. file_info["data_size"] = i32(header_data[16:20])
  95. file_info["pixels_per_meter"] = (
  96. i32(header_data[20:24]),
  97. i32(header_data[24:28]),
  98. )
  99. file_info["colors"] = i32(header_data[28:32])
  100. file_info["palette_padding"] = 4
  101. self.info["dpi"] = tuple(
  102. int(x / 39.3701 + 0.5) for x in file_info["pixels_per_meter"]
  103. )
  104. if file_info["compression"] == self.BITFIELDS:
  105. if len(header_data) >= 52:
  106. for idx, mask in enumerate(
  107. ["r_mask", "g_mask", "b_mask", "a_mask"]
  108. ):
  109. file_info[mask] = i32(header_data[36 + idx * 4 : 40 + idx * 4])
  110. else:
  111. # 40 byte headers only have the three components in the
  112. # bitfields masks, ref:
  113. # https://msdn.microsoft.com/en-us/library/windows/desktop/dd183376(v=vs.85).aspx
  114. # See also
  115. # https://github.com/python-pillow/Pillow/issues/1293
  116. # There is a 4th component in the RGBQuad, in the alpha
  117. # location, but it is listed as a reserved component,
  118. # and it is not generally an alpha channel
  119. file_info["a_mask"] = 0x0
  120. for mask in ["r_mask", "g_mask", "b_mask"]:
  121. file_info[mask] = i32(read(4))
  122. file_info["rgb_mask"] = (
  123. file_info["r_mask"],
  124. file_info["g_mask"],
  125. file_info["b_mask"],
  126. )
  127. file_info["rgba_mask"] = (
  128. file_info["r_mask"],
  129. file_info["g_mask"],
  130. file_info["b_mask"],
  131. file_info["a_mask"],
  132. )
  133. else:
  134. raise IOError("Unsupported BMP header type (%d)" % file_info["header_size"])
  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. # ------------------------------- Check abnormal values for DOS attacks
  145. if file_info["width"] * file_info["height"] > 2 ** 31:
  146. raise IOError("Unsupported BMP Size: (%dx%d)" % self.size)
  147. # ---------------------- Check bit depth for unusual unsupported values
  148. self.mode, raw_mode = BIT2MODE.get(file_info["bits"], (None, None))
  149. if self.mode is None:
  150. raise IOError("Unsupported BMP pixel depth (%d)" % file_info["bits"])
  151. # ---------------- Process BMP with Bitfields compression (not palette)
  152. if file_info["compression"] == self.BITFIELDS:
  153. SUPPORTED = {
  154. 32: [
  155. (0xFF0000, 0xFF00, 0xFF, 0x0),
  156. (0xFF0000, 0xFF00, 0xFF, 0xFF000000),
  157. (0xFF, 0xFF00, 0xFF0000, 0xFF000000),
  158. (0x0, 0x0, 0x0, 0x0),
  159. (0xFF000000, 0xFF0000, 0xFF00, 0x0),
  160. ],
  161. 24: [(0xFF0000, 0xFF00, 0xFF)],
  162. 16: [(0xF800, 0x7E0, 0x1F), (0x7C00, 0x3E0, 0x1F)],
  163. }
  164. MASK_MODES = {
  165. (32, (0xFF0000, 0xFF00, 0xFF, 0x0)): "BGRX",
  166. (32, (0xFF000000, 0xFF0000, 0xFF00, 0x0)): "XBGR",
  167. (32, (0xFF, 0xFF00, 0xFF0000, 0xFF000000)): "RGBA",
  168. (32, (0xFF0000, 0xFF00, 0xFF, 0xFF000000)): "BGRA",
  169. (32, (0x0, 0x0, 0x0, 0x0)): "BGRA",
  170. (24, (0xFF0000, 0xFF00, 0xFF)): "BGR",
  171. (16, (0xF800, 0x7E0, 0x1F)): "BGR;16",
  172. (16, (0x7C00, 0x3E0, 0x1F)): "BGR;15",
  173. }
  174. if file_info["bits"] in SUPPORTED:
  175. if (
  176. file_info["bits"] == 32
  177. and file_info["rgba_mask"] in SUPPORTED[file_info["bits"]]
  178. ):
  179. raw_mode = MASK_MODES[(file_info["bits"], file_info["rgba_mask"])]
  180. self.mode = "RGBA" if "A" in raw_mode else self.mode
  181. elif (
  182. file_info["bits"] in (24, 16)
  183. and file_info["rgb_mask"] in SUPPORTED[file_info["bits"]]
  184. ):
  185. raw_mode = MASK_MODES[(file_info["bits"], file_info["rgb_mask"])]
  186. else:
  187. raise IOError("Unsupported BMP bitfields layout")
  188. else:
  189. raise IOError("Unsupported BMP bitfields layout")
  190. elif file_info["compression"] == self.RAW:
  191. if file_info["bits"] == 32 and header == 22: # 32-bit .cur offset
  192. raw_mode, self.mode = "BGRA", "RGBA"
  193. else:
  194. raise IOError("Unsupported BMP compression (%d)" % 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 IOError("Unsupported BMP Palette size (%d)" % 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. "raw",
  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 head_data[0:2] != b"BM":
  243. raise SyntaxError("Not a BMP file")
  244. # read the start position of the BMP image data (u32)
  245. offset = i32(head_data[10:14])
  246. # load bitmap information (offset=raster info)
  247. self._bitmap(offset=offset)
  248. # =============================================================================
  249. # Image plugin for the DIB format (BMP alias)
  250. # =============================================================================
  251. class DibImageFile(BmpImageFile):
  252. format = "DIB"
  253. format_description = "Windows Bitmap"
  254. def _open(self):
  255. self._bitmap()
  256. #
  257. # --------------------------------------------------------------------
  258. # Write BMP file
  259. SAVE = {
  260. "1": ("1", 1, 2),
  261. "L": ("L", 8, 256),
  262. "P": ("P", 8, 256),
  263. "RGB": ("BGR", 24, 0),
  264. "RGBA": ("BGRA", 32, 0),
  265. }
  266. def _dib_save(im, fp, filename):
  267. _save(im, fp, filename, False)
  268. def _save(im, fp, filename, bitmap_header=True):
  269. try:
  270. rawmode, bits, colors = SAVE[im.mode]
  271. except KeyError:
  272. raise IOError("cannot write mode %s as BMP" % im.mode)
  273. info = im.encoderinfo
  274. dpi = info.get("dpi", (96, 96))
  275. # 1 meter == 39.3701 inches
  276. ppm = tuple(map(lambda x: int(x * 39.3701 + 0.5), dpi))
  277. stride = ((im.size[0] * bits + 7) // 8 + 3) & (~3)
  278. header = 40 # or 64 for OS/2 version 2
  279. image = stride * im.size[1]
  280. # bitmap header
  281. if bitmap_header:
  282. offset = 14 + header + colors * 4
  283. fp.write(
  284. b"BM"
  285. + o32(offset + image) # file type (magic)
  286. + o32(0) # file size
  287. + o32(offset) # reserved
  288. ) # image data offset
  289. # bitmap info header
  290. fp.write(
  291. o32(header) # info header size
  292. + o32(im.size[0]) # width
  293. + o32(im.size[1]) # height
  294. + o16(1) # planes
  295. + o16(bits) # depth
  296. + o32(0) # compression (0=uncompressed)
  297. + o32(image) # size of bitmap
  298. + o32(ppm[0]) # resolution
  299. + o32(ppm[1]) # resolution
  300. + o32(colors) # colors used
  301. + o32(colors) # colors important
  302. )
  303. fp.write(b"\0" * (header - 40)) # padding (for OS/2 format)
  304. if im.mode == "1":
  305. for i in (0, 255):
  306. fp.write(o8(i) * 4)
  307. elif im.mode == "L":
  308. for i in range(256):
  309. fp.write(o8(i) * 4)
  310. elif im.mode == "P":
  311. fp.write(im.im.getpalette("RGB", "BGRX"))
  312. ImageFile._save(im, fp, [("raw", (0, 0) + im.size, 0, (rawmode, stride, -1))])
  313. #
  314. # --------------------------------------------------------------------
  315. # Registry
  316. Image.register_open(BmpImageFile.format, BmpImageFile, _accept)
  317. Image.register_save(BmpImageFile.format, _save)
  318. Image.register_extension(BmpImageFile.format, ".bmp")
  319. Image.register_mime(BmpImageFile.format, "image/bmp")
  320. Image.register_open(DibImageFile.format, DibImageFile, _dib_accept)
  321. Image.register_save(DibImageFile.format, _dib_save)
  322. Image.register_extension(DibImageFile.format, ".dib")
  323. Image.register_mime(DibImageFile.format, "image/bmp")