Yield packed rows that are a byte array. Each byte is packed with the values from several pixels.
(rows, bitdepth)
| 961 | |
| 962 | |
| 963 | def pack_rows(rows, bitdepth): |
| 964 | """Yield packed rows that are a byte array. |
| 965 | Each byte is packed with the values from several pixels. |
| 966 | """ |
| 967 | |
| 968 | assert bitdepth < 8 |
| 969 | assert 8 % bitdepth == 0 |
| 970 | |
| 971 | # samples per byte |
| 972 | spb = int(8 / bitdepth) |
| 973 | |
| 974 | def make_byte(block): |
| 975 | """Take a block of (2, 4, or 8) values, |
| 976 | and pack them into a single byte. |
| 977 | """ |
| 978 | |
| 979 | res = 0 |
| 980 | for v in block: |
| 981 | res = (res << bitdepth) + v |
| 982 | return res |
| 983 | |
| 984 | for row in rows: |
| 985 | a = bytearray(row) |
| 986 | # Adding padding bytes so we can group into a whole |
| 987 | # number of spb-tuples. |
| 988 | n = float(len(a)) |
| 989 | extra = math.ceil(n / spb) * spb - n |
| 990 | a.extend([0] * int(extra)) |
| 991 | # Pack into bytes. |
| 992 | # Each block is the samples for one byte. |
| 993 | blocks = group(a, spb) |
| 994 | yield bytearray(make_byte(block) for block in blocks) |
| 995 | |
| 996 | |
| 997 | def unpack_rows(rows): |
no test coverage detected