Answer the question
In order to leave comments, you need to log in
How to create an empty n*m bmp image in Python without 3rd party libraries?
It is necessary to create an empty bmp image (any set of pixels) of size n * m in Python 3 without third-party libraries and save
Answer the question
In order to leave comments, you need to log in
def createEmptyImage(file, width, height):
w = width
h = height
filesize = 54 + 3 * width * height
img = [0 for i in range(3 * w * h)]
header = [66, 77, 0, 0, 0, 0, 0, 0, 0, 0, 54, 0, 0, 0, 40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 24, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
header[2] = filesize % 256
header[3] = (filesize >> 8) % 256
header[4] = (filesize >> 16) % 256
header[5] = (filesize >> 24) % 256
header[18] = (width) % 256
header[19] = (width >> 8) % 256
header[20] = (width >> 16) % 256
header[21] = (width >> 24) % 256
header[22] = (height) % 256
header[23] = (height >> 8) % 256
header[24] = (height >> 16) % 256
header[25] = (height >> 24) % 256
f = open(file, "wb")
f.write(bytes(header))
for i in range(height):
f.write(bytes(img[(width * (h - i - 1) * 3):(width * (h - i - 1) * 3) + 3 * width]))
f.write(bytes([0, 0, 0][:(4 - (width * 3) % 4) % 4]))
f.close()
You can pull the implementation from some library. For example from here: https://github.com/construct/construct/blob/master...
You can look at my shitcode:
def create_bmp(width, height):
return b'\x42\x4D\x7A'+b'\x00'*7+b'\x7A\x00\x00\x00\x6C\x00\x00\x00' + width.to_bytes(4, 'little') + height.to_bytes(4, 'little') + b'\x01\x00\x18'+b'\x00'*9+b'\x13\x0B'*2+b'\x00'*10+b'RGBr'+b'\x00'*70
with open(sys.argv[1], 'wb') as file:
file.write(create_bmp(128, 256))
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question