CoolFace
Apppublic

Aluode/PerceptionLabPortable

sourceHugging Faceupdated 9mo agoView on Hugging Face
0likes
PaletteFile.py55 linesDownload Raw Back to PIL
1#
2# Python Imaging Library
3# $Id$
4#
5# stuff to read simple, teragon-style palette files
6#
7# History:
8#       97-08-23 fl     Created
9#
10# Copyright (c) Secret Labs AB 1997.
11# Copyright (c) Fredrik Lundh 1997.
12#
13# See the README file for information on usage and redistribution.
14#
15from __future__ import annotations
16
17from typing import IO
18
19from ._binary import o8
20
21
22class PaletteFile:
23    """File handler for Teragon-style palette files."""
24
25    rawmode = "RGB"
26
27    def __init__(self, fp: IO[bytes]) -> None:
28        palette = [o8(i) * 3 for i in range(256)]
29
30        while True:
31            s = fp.readline()
32
33            if not s:
34                break
35            if s.startswith(b"#"):
36                continue
37            if len(s) > 100:
38                msg = "bad palette file"
39                raise SyntaxError(msg)
40
41            v = [int(x) for x in s.split()]
42            try:
43                [i, r, g, b] = v
44            except ValueError:
45                [i, r] = v
46                g = b = r
47
48            if 0 <= i <= 255:
49                palette[i] = o8(r) + o8(g) + o8(b)
50
51        self.palette = b"".join(palette)
52
53    def getpalette(self) -> tuple[bytes, str]:
54        return self.palette, self.rawmode
55 
Aluode/PerceptionLabPortable · CoolFace