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.

331 lines
14 KiB

4 years ago
  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, \
  27. o8, o16le as o16, o32le as o32
  28. import math
  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. # ==============================================================================
  45. # Image plugin for the Windows BMP format.
  46. # ==============================================================================
  47. class BmpImageFile(ImageFile.ImageFile):
  48. """ Image plugin for the Windows Bitmap format (BMP) """
  49. # -------------------------------------------------------------- Description
  50. format_description = "Windows Bitmap"
  51. format = "BMP"
  52. # --------------------------------------------------- BMP Compression values
  53. COMPRESSIONS = {
  54. 'RAW': 0,
  55. 'RLE8': 1,
  56. 'RLE4': 2,
  57. 'BITFIELDS': 3,
  58. 'JPEG': 4,
  59. 'PNG': 5
  60. }
  61. RAW, RLE8, RLE4, BITFIELDS, JPEG, PNG = 0, 1, 2, 3, 4, 5
  62. def _bitmap(self, header=0, offset=0):
  63. """ Read relevant info about the BMP """
  64. read, seek = self.fp.read, self.fp.seek
  65. if header:
  66. seek(header)
  67. file_info = {}
  68. # read bmp header size @offset 14 (this is part of the header size)
  69. file_info['header_size'] = i32(read(4))
  70. file_info['direction'] = -1
  71. # --------------------- If requested, read header at a specific position
  72. # read the rest of the bmp header, without its size
  73. header_data = ImageFile._safe_read(self.fp,
  74. file_info['header_size'] - 4)
  75. # --------------------------------------------------- IBM OS/2 Bitmap v1
  76. # ------ This format has different offsets because of width/height types
  77. if file_info['header_size'] == 12:
  78. file_info['width'] = i16(header_data[0:2])
  79. file_info['height'] = i16(header_data[2:4])
  80. file_info['planes'] = i16(header_data[4:6])
  81. file_info['bits'] = i16(header_data[6:8])
  82. file_info['compression'] = self.RAW
  83. file_info['palette_padding'] = 3
  84. # ---------------------------------------------- Windows Bitmap v2 to v5
  85. elif file_info['header_size'] in (40, 64, 108, 124): # v3, OS/2 v2, v4, v5
  86. if file_info['header_size'] >= 40: # v3 and OS/2
  87. file_info['y_flip'] = i8(header_data[7]) == 0xff
  88. file_info['direction'] = 1 if file_info['y_flip'] else -1
  89. file_info['width'] = i32(header_data[0:4])
  90. file_info['height'] = (i32(header_data[4:8])
  91. if not file_info['y_flip']
  92. else 2**32 - i32(header_data[4:8]))
  93. file_info['planes'] = i16(header_data[8:10])
  94. file_info['bits'] = i16(header_data[10:12])
  95. file_info['compression'] = i32(header_data[12:16])
  96. # byte size of pixel data
  97. file_info['data_size'] = i32(header_data[16:20])
  98. file_info['pixels_per_meter'] = (i32(header_data[20:24]),
  99. i32(header_data[24:28]))
  100. file_info['colors'] = i32(header_data[28:32])
  101. file_info['palette_padding'] = 4
  102. self.info["dpi"] = tuple(
  103. map(lambda x: int(math.ceil(x / 39.3701)),
  104. file_info['pixels_per_meter']))
  105. if file_info['compression'] == self.BITFIELDS:
  106. if len(header_data) >= 52:
  107. for idx, mask in enumerate(['r_mask',
  108. 'g_mask',
  109. 'b_mask',
  110. 'a_mask']):
  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,
  115. # ref: https://msdn.microsoft.com/en-us/library/windows/desktop/dd183376(v=vs.85).aspx
  116. # See also https://github.com/python-pillow/Pillow/issues/1293
  117. # There is a 4th component in the RGBQuad, in the alpha
  118. # location, but it is listed as a reserved component,
  119. # and it is not generally an alpha channel
  120. file_info['a_mask'] = 0x0
  121. for mask in ['r_mask', 'g_mask', 'b_mask']:
  122. file_info[mask] = i32(read(4))
  123. file_info['rgb_mask'] = (file_info['r_mask'],
  124. file_info['g_mask'],
  125. file_info['b_mask'])
  126. file_info['rgba_mask'] = (file_info['r_mask'],
  127. file_info['g_mask'],
  128. file_info['b_mask'],
  129. file_info['a_mask'])
  130. else:
  131. raise IOError("Unsupported BMP header type (%d)" %
  132. 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'] = file_info['colors'] if file_info.get('colors', 0) else (1 << file_info['bits'])
  138. # -------------------------------- Check abnormal values for DOS attacks
  139. if file_info['width'] * file_info['height'] > 2**31:
  140. raise IOError("Unsupported BMP Size: (%dx%d)" % self.size)
  141. # ----------------------- Check bit depth for unusual unsupported values
  142. self.mode, raw_mode = BIT2MODE.get(file_info['bits'], (None, None))
  143. if self.mode is None:
  144. raise IOError("Unsupported BMP pixel depth (%d)"
  145. % file_info['bits'])
  146. # ----------------- Process BMP with Bitfields compression (not palette)
  147. if file_info['compression'] == self.BITFIELDS:
  148. SUPPORTED = {
  149. 32: [(0xff0000, 0xff00, 0xff, 0x0),
  150. (0xff0000, 0xff00, 0xff, 0xff000000),
  151. (0x0, 0x0, 0x0, 0x0),
  152. (0xff000000, 0xff0000, 0xff00, 0x0)],
  153. 24: [(0xff0000, 0xff00, 0xff)],
  154. 16: [(0xf800, 0x7e0, 0x1f), (0x7c00, 0x3e0, 0x1f)]
  155. }
  156. MASK_MODES = {
  157. (32, (0xff0000, 0xff00, 0xff, 0x0)): "BGRX",
  158. (32, (0xff000000, 0xff0000, 0xff00, 0x0)): "XBGR",
  159. (32, (0xff0000, 0xff00, 0xff, 0xff000000)): "BGRA",
  160. (32, (0x0, 0x0, 0x0, 0x0)): "BGRA",
  161. (24, (0xff0000, 0xff00, 0xff)): "BGR",
  162. (16, (0xf800, 0x7e0, 0x1f)): "BGR;16",
  163. (16, (0x7c00, 0x3e0, 0x1f)): "BGR;15"
  164. }
  165. if file_info['bits'] in SUPPORTED:
  166. if file_info['bits'] == 32 and \
  167. file_info['rgba_mask'] in SUPPORTED[file_info['bits']]:
  168. raw_mode = MASK_MODES[(file_info['bits'], file_info['rgba_mask'])]
  169. self.mode = "RGBA" if raw_mode in ("BGRA",) else self.mode
  170. elif (file_info['bits'] in (24, 16) and
  171. file_info['rgb_mask'] in SUPPORTED[file_info['bits']]):
  172. raw_mode = MASK_MODES[
  173. (file_info['bits'], file_info['rgb_mask'])
  174. ]
  175. else:
  176. raise IOError("Unsupported BMP bitfields layout")
  177. else:
  178. raise IOError("Unsupported BMP bitfields layout")
  179. elif file_info['compression'] == self.RAW:
  180. if file_info['bits'] == 32 and header == 22: # 32-bit .cur offset
  181. raw_mode, self.mode = "BGRA", "RGBA"
  182. else:
  183. raise IOError("Unsupported BMP compression (%d)" %
  184. file_info['compression'])
  185. # ---------------- Once the header is processed, process the palette/LUT
  186. if self.mode == "P": # Paletted for 1, 4 and 8 bit images
  187. # ----------------------------------------------------- 1-bit images
  188. if not (0 < file_info['colors'] <= 65536):
  189. raise IOError("Unsupported BMP Palette size (%d)" %
  190. file_info['colors'])
  191. else:
  192. padding = file_info['palette_padding']
  193. palette = read(padding * file_info['colors'])
  194. greyscale = True
  195. indices = (0, 255) if file_info['colors'] == 2 else \
  196. list(range(file_info['colors']))
  197. # ------------------ Check if greyscale and ignore palette if so
  198. for ind, val in enumerate(indices):
  199. rgb = palette[ind*padding:ind*padding + 3]
  200. if rgb != o8(val) * 3:
  201. greyscale = False
  202. # -------- If all colors are grey, white or black, ditch palette
  203. if greyscale:
  204. self.mode = "1" if file_info['colors'] == 2 else "L"
  205. raw_mode = self.mode
  206. else:
  207. self.mode = "P"
  208. self.palette = ImagePalette.raw(
  209. "BGRX" if padding == 4 else "BGR", palette)
  210. # ----------------------------- Finally set the tile data for the plugin
  211. self.info['compression'] = file_info['compression']
  212. self.tile = [
  213. ('raw',
  214. (0, 0, file_info['width'], file_info['height']),
  215. offset or self.fp.tell(),
  216. (raw_mode,
  217. ((file_info['width'] * file_info['bits'] + 31) >> 3) & (~3),
  218. file_info['direction']))
  219. ]
  220. def _open(self):
  221. """ Open file, check magic number and read header """
  222. # read 14 bytes: magic number, filesize, reserved, header final offset
  223. head_data = self.fp.read(14)
  224. # choke if the file does not have the required magic bytes
  225. if head_data[0:2] != b"BM":
  226. raise SyntaxError("Not a BMP file")
  227. # read the start position of the BMP image data (u32)
  228. offset = i32(head_data[10:14])
  229. # load bitmap information (offset=raster info)
  230. self._bitmap(offset=offset)
  231. # ==============================================================================
  232. # Image plugin for the DIB format (BMP alias)
  233. # ==============================================================================
  234. class DibImageFile(BmpImageFile):
  235. format = "DIB"
  236. format_description = "Windows Bitmap"
  237. def _open(self):
  238. self._bitmap()
  239. #
  240. # --------------------------------------------------------------------
  241. # Write BMP file
  242. SAVE = {
  243. "1": ("1", 1, 2),
  244. "L": ("L", 8, 256),
  245. "P": ("P", 8, 256),
  246. "RGB": ("BGR", 24, 0),
  247. "RGBA": ("BGRA", 32, 0),
  248. }
  249. def _save(im, fp, filename):
  250. try:
  251. rawmode, bits, colors = SAVE[im.mode]
  252. except KeyError:
  253. raise IOError("cannot write mode %s as BMP" % im.mode)
  254. info = im.encoderinfo
  255. dpi = info.get("dpi", (96, 96))
  256. # 1 meter == 39.3701 inches
  257. ppm = tuple(map(lambda x: int(x * 39.3701), dpi))
  258. stride = ((im.size[0]*bits+7)//8+3) & (~3)
  259. header = 40 # or 64 for OS/2 version 2
  260. offset = 14 + header + colors * 4
  261. image = stride * im.size[1]
  262. # bitmap header
  263. fp.write(b"BM" + # file type (magic)
  264. o32(offset+image) + # file size
  265. o32(0) + # reserved
  266. o32(offset)) # image data offset
  267. # bitmap info header
  268. fp.write(o32(header) + # info header size
  269. o32(im.size[0]) + # width
  270. o32(im.size[1]) + # height
  271. o16(1) + # planes
  272. o16(bits) + # depth
  273. o32(0) + # compression (0=uncompressed)
  274. o32(image) + # size of bitmap
  275. o32(ppm[0]) + o32(ppm[1]) + # resolution
  276. o32(colors) + # colors used
  277. o32(colors)) # colors important
  278. fp.write(b"\0" * (header - 40)) # padding (for OS/2 format)
  279. if im.mode == "1":
  280. for i in (0, 255):
  281. fp.write(o8(i) * 4)
  282. elif im.mode == "L":
  283. for i in range(256):
  284. fp.write(o8(i) * 4)
  285. elif im.mode == "P":
  286. fp.write(im.im.getpalette("RGB", "BGRX"))
  287. ImageFile._save(im, fp, [("raw", (0, 0)+im.size, 0,
  288. (rawmode, stride, -1))])
  289. #
  290. # --------------------------------------------------------------------
  291. # Registry
  292. Image.register_open(BmpImageFile.format, BmpImageFile, _accept)
  293. Image.register_save(BmpImageFile.format, _save)
  294. Image.register_extension(BmpImageFile.format, ".bmp")
  295. Image.register_mime(BmpImageFile.format, "image/bmp")