Reputation: 2251
I need to read a bitmap image file (.bmp) and split the binary data into an array of bytes, which I can then reconstitute into the original file. Eventually, I will be modifying part of each byte to store data and then reading it to get the data back.
Currently, I am using
file = open("example.bmp","rb")
data = file.read()
file.close()
to get the data. However, this is rather slow and inefficient. Next I want to split it into a byte array, and change the last bit to 0 for each bit that is not part of the metadata (I will use if
statements to subtract 1 from each odd byte). Then I will re-merge the data, and save it into a new image file with the following code:
file = open("example2.bmp","wb")
file.write(data)
file.close()
although I suspect this may be sub-optimal too.
I need to know how to split a lot of binary data into bytes.
Upvotes: 4
Views: 18444
Reputation: 13158
data
is already a byte array, which you can index with slice notation. For example, according to the BMP file format, the Bitmap File Header is in data[0:14]
. You may want to instead use C libraries in Python to save yourself some time.
Upvotes: 5