Donno how to compress the idat chunk properly without writing the whole function myself and dumping the zlib
(img, path="image.bmp")
| 511 | |
| 512 | |
| 513 | def write_as_bmp(img, path="image.bmp"): |
| 514 | """ |
| 515 | Donno how to compress the idat chunk properly without |
| 516 | writing the whole function myself and dumping the zlib |
| 517 | """ |
| 518 | if not path.endswith(".bmp"): |
| 519 | path += ".bmp" |
| 520 | if isinstance(img, Png): |
| 521 | img = img.pixels |
| 522 | |
| 523 | width = len(img[0]) |
| 524 | height = len(img) |
| 525 | size = 54 + 4 * ceil(width/4) * height * 3 |
| 526 | header = (b'BM' + |
| 527 | size.to_bytes(4, "little") + |
| 528 | (0).to_bytes(2, "little") + |
| 529 | (0).to_bytes(2, "little") + |
| 530 | (54).to_bytes(4, "little")) |
| 531 | |
| 532 | dib_header = ( |
| 533 | (40).to_bytes(4, "little") + |
| 534 | width.to_bytes(4, "little") + |
| 535 | height.to_bytes(4, "little") + |
| 536 | (1).to_bytes(2, "little") + |
| 537 | (24).to_bytes(2, "little") + # bit depth |
| 538 | (0).to_bytes(4, "little") + # No compression |
| 539 | (0).to_bytes(4, "little") + |
| 540 | (1).to_bytes(4, "little") + |
| 541 | (1).to_bytes(4, "little") + |
| 542 | (0).to_bytes(4, "little") + |
| 543 | (0).to_bytes(4, "little") |
| 544 | ) |
| 545 | pixels = [] |
| 546 | img.reverse() |
| 547 | for row in img: |
| 548 | for pixel in row: |
| 549 | pixels.append(pixel[2].to_bytes(1, 'little')) |
| 550 | pixels.append(pixel[1].to_bytes(1, 'little')) |
| 551 | pixels.append(pixel[0].to_bytes(1, 'little')) |
| 552 | pixels.append(b'\x00' * (width % 4)) |
| 553 | pixels = b''.join(pixels) |
| 554 | with open(path, "wb") as image_file: |
| 555 | image_file.write(header + dib_header + b"\x00" * 6 + pixels) |
| 556 | |
| 557 | |
| 558 |
no outgoing calls
no test coverage detected