from PIL import Image

def text_to_bin(text):
    return ''.join(format(ord(i), '08b') for i in text)

def encode_image(img_path, message, output_path):
    img = Image.open(img_path).convert('RGB')
    binary_msg = text_to_bin(message) + '1111111111111110'
    pixels = img.load()
    width, height = img.size
    data_index = 0

    for y in range(height):
        for x in range(width):
            r, g, b = pixels[x, y]
            if data_index < len(binary_msg):
                r = (r & ~1) | int(binary_msg[data_index]); data_index += 1
            if data_index < len(binary_msg):
                g = (g & ~1) | int(binary_msg[data_index]); data_index += 1
            if data_index < len(binary_msg):
                b = (b & ~1) | int(binary_msg[data_index]); data_index += 1
            pixels[x, y] = (r, g, b)
            if data_index >= len(binary_msg):
                img.save(output_path)
                return True
    return False

def decode_image(img_path):
    img = Image.open(img_path).convert('RGB')
    binary_data = ""
    pixels = img.load()
    for y in range(img.height):
        for x in range(img.width):
            r, g, b = pixels[x, y]
            binary_data += str(r & 1) + str(g & 1) + str(b & 1)

    all_bytes = [binary_data[i:i+8] for i in range(0, len(binary_data), 8)]
    decoded_text = ""
    for byte in all_bytes:
        if byte == "11111111": break
        decoded_text += chr(int(byte, 2))
    return decoded_text
