Skip to content

Instantly share code, notes, and snippets.

@Intedai
Last active May 18, 2023 16:40
Show Gist options
  • Save Intedai/89e2a09d5b21eed968aa51ba38eaf000 to your computer and use it in GitHub Desktop.
Save Intedai/89e2a09d5b21eed968aa51ba38eaf000 to your computer and use it in GitHub Desktop.
Paint.NET Palette File Parser
from typing import TextIO # For type hinting for the file object in parse_palette
def parse_palette(file: TextIO) -> list:
"""
Parses Paint.NET palette files into a python list that contains the strings of the hex color values:
parses the colors,
pads hex colors that their length is smaller than 8 with the needed amount of 0's,
if line contains non hex characters or it has more than 8 characters it skips them (also skips ; comments),
and it adds "FFFFFFFF" to the list until it has 96 colors if needed
and it skips the rest of the lines if it has 96 colors.
:param file TextIO: The person sending the message
:return: the parsed palette list
:rtype: list
"""
# Hex characters for checking if the line is a hex color value
hex_chars = set("0123456789abcdefABCDEF")
# Where the colors will be stored
palette_list = []
for line in file:
stripped_line = line.strip()
# Paint.NET palette file allows only 96 colors max
if len(palette_list) >= 96:
break
# Check if contains non hex character and also skips ; comments and continues if the hex value is bigger than 8
elif (
not all(char in "0123456789abcdefABCDEF" for char in stripped_line)
or stripped_line == ""
or len(stripped_line) > 8
):
continue
else:
# Add 0 padding to the hex values if needed and append to the list
palette_list.append(stripped_line.zfill(8))
# Append white to the list until it reaches 96 colors if it has less than 96 colors
while len(palette_list) < 96:
palette_list.append("FFFFFFFF")
# Return the completed list
return palette_list
if __name__ == "__main__":
# Opens your palette file and prints the list
with open("palette_file.txt", "r") as file:
print(parse_palette(file))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment