import io
import struct


def generate_bmp(img_data):
    """Generate a BMP format image from pixel data"""

    bmp = io.BytesIO()

    height = len(img_data)
    width = len(img_data[0])

    # rgb
    bpp = 24
    color_table_entries = 0

    row_size = int((bpp*width + 31)/32)*4
    image_size = row_size * height
    header_size = 14+40
    color_table_size = color_table_entries*4
    image_offset = header_size+color_table_size
    file_size = image_offset+image_size

    # bitmap header
    bmp.write(b'BM')
    bmp.write(struct.pack('<L', file_size)) # file size
    bmp.write(struct.pack('<H', 0)) # reserved
    bmp.write(struct.pack('<H', 0)) # reserved
    bmp.write(struct.pack('<L', image_offset)) # offset to bitmap data
    # bitmapinfoheader
    bmp.write(struct.pack('<L', 40)) # size of header
    bmp.write(struct.pack('<l', width)) # image width
    bmp.write(struct.pack('<l', height)) # image height
    bmp.write(struct.pack('<H', 1)) # number of color planes
    bmp.write(struct.pack('<H', bpp)) # bits per pixel
    bmp.write(struct.pack('<L', 0)) # compression method
    bmp.write(struct.pack('<L', image_size)) # image size
    bmp.write(struct.pack('<L', 1)) # horizontal resolution
    bmp.write(struct.pack('<L', 1)) # vertical resolution
    bmp.write(struct.pack('<L', color_table_entries)) # number of colors in palette (0 = 2^n)
    bmp.write(struct.pack('<L', 0)) # number of important colors in palette (0 = all)

    # rgb

    # color table
    # no color table for RGB

    # image data
    for y in range(height-1, -1, -1):
        for x in range(width):
            bmp.write(struct.pack('<BBB', img_data[y][x][2], img_data[y][x][1], img_data[y][x][0]))
        if (width*3) % 4 > 0:
            for x in range(4 - ((width*3) % 4)):
                bmp.write(b'\0')

    return bmp.getvalue()