Advertisement
Guest User

writeBMP

a guest
Apr 26th, 2015
227
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.83 KB | None | 0 0
  1. import struct
  2.  
  3. def writeBMP(filename, matrix):
  4.     height = len(matrix)
  5.     if height < 1:
  6.         raise Exception('Height must be >0')
  7.     width = len(matrix[0])
  8.     if width < 1:
  9.         raise Exception('Width must be >0')
  10.     data = sum(reversed(matrix), [])
  11.     with open(filename, 'wb') as file:
  12.         file.write(struct.pack('<H', 0x4D42)) # Signature.
  13.         file.write(struct.pack('<I', width * height * 4 + 54)) # File size
  14.         file.write(struct.pack('<III', 0, 0x36, 0x28)) # Offset and other tech data.
  15.         file.write(struct.pack('<ii', width, height))
  16.         file.write(struct.pack('<HH', 1, 0x20)) # Tech data and bitcount.
  17.         file.write(struct.pack('<IIiiII', 0, 0, 0, 0, 0, 0,)) # Zeroes.
  18.         for pixel in data:
  19.             r, g, b = pixel
  20.             file.write(struct.pack('<BBBB', b, g, r, 0xFF))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement