]>
Commit | Line | Data |
---|---|---|
596cd671 | 1 | # bmp - bitmap processing |
668f4f77 | 2 | # ref: https://en.wikipedia.org/wiki/BMP_file_format |
596cd671 | 3 | |
4 | from struct import unpack | |
5 | ||
6 | class FormatError(Exception): pass | |
7 | class MagicError(FileFormatError): pass | |
8 | class CompressionError(FormatError): pass | |
9 | class BppError(FormatError): pass | |
10 | ||
11 | class Bmp(object): | |
12 | def __init__(self, fn_or_fo): | |
13 | fo = fn_or_fo | |
14 | if isinstance(fn_or_fo, basestring): | |
15 | fo = open(fn, 'rb') | |
16 | self.fo = fo | |
17 | self._read() | |
18 | def _read(self): | |
19 | header = self.fo.read(14) | |
20 | magic, filesize, start_address = unpack("<2sI2x2xI", header) | |
21 | if magic != "BM": raise MagicError("wrong BMP header magic") | |
22 | dib = self.fo.read(40) | |
23 | magic, pixelwidth, pixelheight, bpp, compression = unpack("<III2xHI4x4x4x4x4x", dib) | |
24 | if magic != 40: raise MagicError("wrong DIB header magic") | |
25 | if compression != 0: raise CompressionError("compression not supported") |