Skip to content

Instantly share code, notes, and snippets.

@watbulb
Last active December 10, 2020 22:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save watbulb/43e72ff49bffe440437f94064f0bdb8b to your computer and use it in GitHub Desktop.
Save watbulb/43e72ff49bffe440437f94064f0bdb8b to your computer and use it in GitHub Desktop.
Universal Device Independant Bitmap (DIB) to BMP Converter
#!/usr/bin/env python3
'''
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
Universal DIB to BMP converter. <d$pid>
'''
import sys
import math
from binascii import hexlify
def usage():
print("python {} <path to DIB file> <output file path>".format(sys.argv[0]))
sys.exit(0)
def conv(size):
return ''.join(map(chr, [size & 0xFF, (size >> 8) & 0xFF, (size >> 16) & 0xFF, (size >> 24) & 0xFF]))
def length():
try:
with open(sys.argv[1], 'rb') as fd:
length = len(fd.read())
fd.close()
return length
except Exception:
raise Exception
def prepend(data, path):
try:
with open(sys.argv[1], 'rb') as fd:
original = fd.read()
fd.close()
with open(path, 'wb') as fd:
new = data + original
fd.write(new)
fd.close()
except Exception:
raise Exception
if __name__ == '__main__':
if len(sys.argv) <= 2:
usage()
offset = int(54 + math.pow(2, 1) * 4)
# Header Generation
data = 'BM'.encode() # ID Field
data += conv(offset + length()).encode() # BMP Size
data += conv(0).encode() # Unused
data += conv(offset).encode() # Pixel Data Offset
print("[DIB TOOL] Crafting header...")
print("[DIB TOOL] Header crafted for file: {}\n\n\t{}\n".format(
sys.argv[1], hexlify(data)))
print("[DIB TOOL] Prepending header to new file: {}".format(sys.argv[2]))
# Prepend Crafted Header to File
prepend(data, sys.argv[2])
print("[DIB TOOL] Done")
@sfnagle
Copy link

sfnagle commented Dec 10, 2020

This doesn't seem to work. I tried it on some files I was able to able to convert with an online convertor. But I'd love to do it in Python. Any help would be appreciated. Unfortunately github won't let me share the DIB file here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment