def loadIndexedBitmap(stream): # read file header fileHeader = readStruct(stream, "<2sIHHI") if fileHeader[0] != b"BM": return 0, 0, None, None bmpHeaderSize = readStruct(stream, "I")[0] bmpHeader = stream.read(bmpHeaderSize - 4) ( biWidth, biHeight, biPlanes, biBitCount, biCompression, biSizeImage, biXPelsPerMeter, biYPelsPerMeter, biClrUsed, biClrImportant, ) = struct.unpack("iiHHIIiiII", bmpHeader[0:36]) if biBitCount != 8: return 0, 0, None, None # read color table if biClrUsed == 0: biClrUsed = 256 colorTableData = stream.read(biClrUsed * 4) pixelCount = biWidth * biHeight pixelData = stream.read(pixelCount) colorUse = [0 for i in range(0, 256)] for p in pixelData: colorUse[p] += 1 colors = [] for i, use in zip(range(0, biClrUsed * 4, 4), colorUse): b, g, r, x = colorTableData[i : i + 4] colors.append((r, g, b, x, use)) pixels = [] pos = 0 for i in range(0, biHeight): row = list(pixelData[pos : pos + biWidth]) pixels.append(row) pos += biWidth return biWidth, biHeight, pixels, colors
def loadIndexedBitmap(stream, masked): # read file header fileHeader = readStruct(stream, "<2sIHHI") if fileHeader[0] != b"BM": return 0, 0, None bmpHeaderSize = readStruct(stream, "I")[0] bmpHeader = stream.read(bmpHeaderSize - 4) (biWidth, biHeight, biPlanes, biBitCount, biCompression, biSizeImage, biXPelsPerMeter, biYPelsPerMeter, biClrUsed, biClrImportant) = struct.unpack("iiHHIIiiII", bmpHeader[0:36]) if biBitCount != 8: return 0, 0, None # read color table if biClrUsed == 0: biClrUsed = 256 colorTableData = stream.read(biClrUsed * 4) colors = [] transparent = (0.0, 0.0, 0.0, 0.0) for i in range(0, biClrUsed * 4, 4): b, g, r, x = colorTableData[i : i + 4] colors.append((r / 255.0, g / 255.0, b / 255.0, 1.0)) #if masked: # colors[0] = (1.0, 1.0, 1.0, 0.0) # read pixels pixelCount = biWidth * biHeight pixelData = stream.read(pixelCount) pixels = [] if masked: colors[pixelData[0]] = transparent for i in range(0, pixelCount): try: p = pixelData[i] pixels.extend(colors[p]) except IndexError as e: pixels.extend(transparent) return biWidth, biHeight, pixels