I need to read the header of a bmp file with python. I tried like this but it obviously returns just a bunch of non intelligible bytes:
f = open(input_filename,\
You can use the imghdr module (which is in the python stdlib):
>>> import imghdr
>>> print(imghdr.what(input_filename))
bmp
This will extract the image type from the header, but that is all. There is nothing else in the Python standard library that can get more detailed information - you need a third-party library to do such a specialized task. To get an idea of the complexity of this, take at look at BMP file format. Based on the specification outlined there, it might be feasible to write some pure Python code to extract a few items of information, but it won't be easy to get it right for an arbitrary bitmap image file.
UPDATE:
Below is a simple script to extract some basic information from a bitmap header using the struct module. See the BMP file format mentioned above for how to interpret the various values, and note that this script will only work with the most common version of the format (i.e. Windows BITMAPINFOHEADER):
import struct
bmp = open(fn, 'rb')
print('Type:', bmp.read(2).decode())
print('Size: %s' % struct.unpack('I', bmp.read(4)))
print('Reserved 1: %s' % struct.unpack('H', bmp.read(2)))
print('Reserved 2: %s' % struct.unpack('H', bmp.read(2)))
print('Offset: %s' % struct.unpack('I', bmp.read(4)))
print('DIB Header Size: %s' % struct.unpack('I', bmp.read(4)))
print('Width: %s' % struct.unpack('I', bmp.read(4)))
print('Height: %s' % struct.unpack('I', bmp.read(4)))
print('Colour Planes: %s' % struct.unpack('H', bmp.read(2)))
print('Bits per Pixel: %s' % struct.unpack('H', bmp.read(2)))
print('Compression Method: %s' % struct.unpack('I', bmp.read(4)))
print('Raw Image Size: %s' % struct.unpack('I', bmp.read(4)))
print('Horizontal Resolution: %s' % struct.unpack('I', bmp.read(4)))
print('Vertical Resolution: %s' % struct.unpack('I', bmp.read(4)))
print('Number of Colours: %s' % struct.unpack('I', bmp.read(4)))
print('Important Colours: %s' % struct.unpack('I', bmp.read(4)))
output:
Type: BM
Size: 287518
Reserved 1: 0
Reserved 2: 0
Offset: 1078
DIB Header Size: 40
Width: 657
Height: 434
Colour Planes: 1
Bits per Pixel: 8
Compression Method: 0
Raw Image Size: 286440
Horizontal Resolution: 11811
Vertical Resolution: 11811
Number of Colours: 256
Important Colours: 0