from PIL import Image

# Load the image
image_file = "characters.png"  # Replace with your image file path
image = Image.open(image_file).convert("RGBA")  # Ensure image is in RGBA mode

# Define the characters in order and their corresponding indices
characters = ["A", "B", "C", "D", "E","F","G","H", "I", "J", "K", "L","M","N","O","P", "Q", "R", "S", "T","U","V","W","X", "Y", "Z", "~", "!", "@","#","$","%","^","&","asterisk","(",")","_","-","+","=","`","{","}","seperator","[","]","back_slash","colon",";","double_quote","'","less_than","greater_than", "question_mark", ",", "period","forward_slash"]

# Function to find character widths
def get_character_widths(img):
    widths = []
    current_width = 0
    for x in range(img.width):
        column = [img.getpixel((x, y))[3] for y in range(img.height)]  # Get the alpha value of each pixel in the column
        if all(alpha == 0 for alpha in column):  # Check if all pixels in the column are fully transparent
            if current_width > 0:
                widths.append(current_width)
                current_width = 0
        else:
            current_width += 1
    if current_width > 0:  # Add the last character width if needed
        widths.append(current_width)
    return widths

# Get the widths of each character
widths = get_character_widths(image)

# Check if the number of widths matches the number of characters
print(f'len(widths): {len(widths)}')
print(f'len(characters): {len(characters)}')

assert len(widths) == len(characters), "The number of widths does not match the number of characters."

# Finally, save each character as a separate PNG
current_x = 0
for char, width in zip(characters, widths):
    char_image = image.crop((current_x, 0, current_x + width, image.height))
    print(f"saving {char}")
    char_image.save(f"{char}.png")  # Save the character image as PNG
    current_x += width + 1  # Assume there's a 1 pixel separator column

print("Characters have been saved to individual PNG files.")