Skip to content

Commit

Permalink
Merge pull request #1 from radarhere/gimppalette
Browse files Browse the repository at this point in the history
Only use colors from the palette file
  • Loading branch information
jsbueno authored Oct 6, 2022
2 parents 681f77a + 4642e02 commit 1ed6039
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 34 deletions.
29 changes: 6 additions & 23 deletions Tests/test_file_gimppalette.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,17 +29,8 @@ def test_get_palette():
palette, mode = palette_file.getpalette()

# Assert
assert mode == "RGB"


def test_palette__has_correct_color_indexes():
# Arrange
with open("Tests/images/custom_gimp_palette.gpl", "rb") as fp:
palette_file = GimpPaletteFile(fp)

palette, mode = palette_file.getpalette()

colors_in_test_palette = [
expected_palette = b""
for color in (
(0, 0, 0),
(65, 38, 30),
(103, 62, 49),
Expand All @@ -48,15 +39,7 @@ def test_palette__has_correct_color_indexes():
(208, 127, 100),
(151, 144, 142),
(221, 207, 199),
]

for i, color in enumerate(colors_in_test_palette):
assert tuple(palette[i * 3 : i * 3 + 3]) == color


def test_palette_counts_number_of_colors_in_file():
# Arrange
with open("Tests/images/custom_gimp_palette.gpl", "rb") as fp:
palette_file = GimpPaletteFile(fp)

assert palette_file.n_colors == 8
):
expected_palette += bytes(color)
assert palette == expected_palette
assert mode == "RGB"
21 changes: 10 additions & 11 deletions src/PIL/GimpPaletteFile.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,28 +26,27 @@ class GimpPaletteFile:

def __init__(self, fp):

palette = bytearray(b"".join([o8(i) * 3 for i in range(256)]))

if fp.readline()[:12] != b"GIMP Palette":
raise SyntaxError("not a GIMP palette file")

index = 0
for s in fp:
self.palette = b""
while len(self.palette) < 768:

s = fp.readline()
if not s:
break

# skip fields and comment lines
if re.match(rb"\w+:|#", s):
continue
if len(s) > 100:
raise SyntaxError("bad palette file")

v = tuple(map(int, s.split()[:3]))
v = s.split()
if len(v) < 3:
raise ValueError("bad palette entry")

palette[index * 3 : index * 3 + 3] = v
index += 1

self.palette = bytes(palette)
self.n_colors = index
for i in range(3):
self.palette += o8(int(v[i]))

def getpalette(self):

Expand Down

0 comments on commit 1ed6039

Please sign in to comment.