views:

120

answers:

2

Hi all,
given a somewhat complex file of unknown specification that among other things contains an uncompressed bitmap file (.BMP), how would you extract it in Python?
Scan for the "BM" tag and see if the following bytes "resemble" a BMP header?

+3  A: 

I'd use the Python Imaging Library PIL and have it a go at the data. If it can parse it, then it's a valid image. When it throws an exception, then it isn't.

You need to search for the begining of the image; if you're lucky, the image reader will ignore garbage after the image data. When it doesn't, use a binary search to locate the end of the image.

Aaron Digulla
But what if the file contains other stuff beside the image? Will it be able to extract it ? It would also have to search for it.
Geo
+3  A: 

Yes, about the only thing you can do is search through the file for the 'BM' marker, pull out the following data into a BITMAPFILEHEADER and corresponding BITMAPINFO, and see if the values in it look valid (i.e. that the dimensions are sensible, colour depth is reasonable, etc).

Once you have found something that looks reasonable, pull that data out and pass it to the library mentioned in another answer.

MrZebra