def rgb_to_bitmap(rgb_data, bytes_per_pixel: int, w: int, h: int): log("rgb_to_bitmap%s", (rgb_data, bytes_per_pixel, w, h)) assert bytes_per_pixel in (3, 4) #only BGRA or BGR are supported assert w > 0 and h > 0 header = BITMAPV5HEADER() header.bV5Size = sizeof(BITMAPV5HEADER) header.bV5Width = w header.bV5Height = -h header.bV5Planes = 1 header.bV5BitCount = bytes_per_pixel * 8 header.bV5Compression = BI_RGB #BI_BITFIELDS #header.bV5RedMask = 0x000000ff #header.bV5GreenMask = 0x0000ff00 #header.bV5BlueMask = 0x00ff0000 #header.bV5AlphaMask = 0xff000000 bitmap = 0 try: hdc = GetDC(None) dataptr = c_void_p() log("GetDC()=%#x", hdc) bitmap = CreateDIBSection(hdc, byref(header), win32con.DIB_RGB_COLORS, byref(dataptr), None, 0) finally: ReleaseDC(None, hdc) if not dataptr or not bitmap: raise ctypes.WinError(ctypes.get_last_error()) log("CreateDIBSection(..) got bitmap=%#x, dataptr=%s", int(bitmap), dataptr) img_data = create_string_buffer(rgb_data) ctypes.memmove(dataptr, byref(img_data), w * h * bytes_per_pixel) return bitmap
def rgba_to_bitmap(rgba, w, h): header = BITMAPV5HEADER() header.bV5Size = sizeof(BITMAPV5HEADER) header.bV5Width = w header.bV5Height = -h header.bV5Planes = 1 header.bV5BitCount = 32 header.bV5Compression = BI_RGB #BI_BITFIELDS #header.bV5RedMask = 0x000000ff #header.bV5GreenMask = 0x0000ff00 #header.bV5BlueMask = 0x00ff0000 #header.bV5AlphaMask = 0xff000000 bitmap = 0 try: hdc = GetDC(None) dataptr = c_void_p() log("GetDC()=%#x", hdc) bitmap = CreateDIBSection(hdc, byref(header), win32con.DIB_RGB_COLORS, byref(dataptr), None, 0) finally: ReleaseDC(None, hdc) assert dataptr and bitmap, "failed to create DIB section" log("CreateDIBSection(..) got bitmap=%#x, dataptr=%s", int(bitmap), dataptr) img_data = create_string_buffer(rgba) ctypes.memmove(dataptr, byref(img_data), w * 4 * h) return bitmap