4

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.

Details

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.

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks! Do you have any suggestions for reading the data quickly?
That's about the fastest way to read a file, assuming it all fits into memory. Are you sure that's the slow part of the program?
Yes - testing in isolation, it's frozen a number of times, even while reading smaller bitmaps.
The problem may be with your file system. The files could be locked or the network may be slow. Copy the files to your local disk first.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.