Merge pull request #1 from radarhere/gimppalette

Only use colors from the palette file
This commit is contained in:
Joao S. O. Bueno 2022-10-06 10:21:28 -03:00 committed by GitHub
commit 1ed6039c85
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 16 additions and 34 deletions

View File

@ -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),
@ -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"

View File

@ -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):