Skip to content

Instantly share code, notes, and snippets.

@LockBlock-dev
Last active December 28, 2022 17:11
Show Gist options
  • Save LockBlock-dev/d77e000f221031b506625283ac80b576 to your computer and use it in GitHub Desktop.
Save LockBlock-dev/d77e000f221031b506625283ac80b576 to your computer and use it in GitHub Desktop.
Extract BMP images from a file using Python
# Credits: https://gist.github.com/NanoDano/e092cf9f219e4b0506743bb64d303452?permalink_comment_id=3751054#gistcomment-3751054
import os
import sys
if len(sys.argv) < 2:
sys.exit(f"Usage: sys.argv[0] <file>")
filename = sys.argv[1]
bin = open(filename, "rb")
bin.seek(0, os.SEEK_END) # Seek to the end
filesize = bin.tell() # Get the file size
pos = 0
count = 0
folder = f"{filename}_extracted"
if not os.path.exists(folder):
os.mkdir(folder)
while pos < filesize:
bin.seek(pos)
# Check the first 2 bytes for BMP signature
header = bin.read(2)
if header == b"BM":
# Read the size (4 bytes unsigned little-endian integer) of the image
size = int.from_bytes(bin.read(4), byteorder="little", signed=False)
if not (size > (filesize - pos)):
print(f"offset {hex(pos)} - {size} bytes")
# Go back to beginning of the image
bin.seek(pos)
# Extract the BMP image
image = bin.read(size)
out = open(f"{folder}/{pos}.bmp", "wb")
out.write(image)
out.close()
# Set the current position to the end of the image
pos += size
count += 1
else:
pos += 1
else:
# If the first 2 bytes are not a BMP header, move to the next byte
pos += 1
bin.close()
print(f"Extracted {count} BMP image(s).")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment