我想在python中创建一个bmp图像而不使用任何内置库,如下图像:
请告诉我该怎么做?
答案 0 :(得分:8)
使用BMP file format,您只需创建自己的BMP文件:
import math
import struct
width = 200
height = 200
bits_per_pixel = 24
# bitmap file header
data = 'BM' # Windows 3.1x, 95, NT, ... etc.
data += struct.pack('i', 26 + bits_per_pixel / 8 * width * height) # The size of the BMP file in bytes = header + (color bytes * w * h)
data += struct.pack('h', 0) # Reserved
data += struct.pack('h', 0) # Reserved
data += struct.pack('i', 26) # The offset, i.e. starting address, of the byte where the bitmap image data (pixel array) can be found.
# bitmap header (BITMAPCOREHEADER)
data += struct.pack('i', 12) # The size of this header (12 bytes)
data += struct.pack('h', width) # width
data += struct.pack('h', height) # height
data += struct.pack('h', 1) # The number of color planes, must be 1
data += struct.pack('h', bits_per_pixel) # The number of bits per pixel, which is the color depth of the image. Typical values are 1, 4, 8, 16, 24 and 32.
def rgb_to_bmp_data(r, g, b):
return chr(b) + chr(g) + chr(r)
row_bytes = width * (bits_per_pixel / 8)
row_padding = int(math.ceil(row_bytes / 4.0)) * 4 - row_bytes
for y in xrange(height - 1, -1, -1):
for x in xrange(width):
if (y / 25) % 2:
if (x / 25) % 2:
data += rgb_to_bmp_data(255, 255, 255)
else:
data += rgb_to_bmp_data(0, 0, 0)
else:
if (x / 25) % 2:
data += rgb_to_bmp_data(0, 0, 0)
else:
data += rgb_to_bmp_data(255, 255, 255)
# add padding
data += '\x00' * row_padding
with open('out.bmp', 'wb') as f:
f.write(data)
图像结果接近您的需要: