from PIL import Image

ESC = b"\x1b"

def image_to_sbpl(path, width_px, height_px):
    img = Image.open(path).convert("1")  # PB 1-bit
    img = img.resize((width_px, height_px), Image.NEAREST)

    pixels = img.load()
    bytes_per_row = (width_px + 7) // 8  # garante múltiplo de 8
    data = bytearray()

    for y in range(height_px):
        byte = 0
        bit = 7

        for x in range(width_px):
            if pixels[x, y] == 0:  # preto
                byte |= (1 << bit)

            bit -= 1

            if bit < 0:
                data.append(byte)
                byte = 0
                bit = 7

        # garante que o último byte da linha seja enviado
        if bit != 7:
            data.append(byte)

    header = (
        ESC + b"GF" +
        f"{bytes_per_row:04d}".encode("ascii") +
        f"{height_px:04d}".encode("ascii")
    )

    return header + bytes(data)
