File size: 1,815 Bytes
9c6594c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#
# Python Imaging Library
# $Id$
#
# stuff to read GIMP palette files
#
# History:
# 1997-08-23 fl     Created
# 2004-09-07 fl     Support GIMP 2.0 palette files.
#
# Copyright (c) Secret Labs AB 1997-2004.  All rights reserved.
# Copyright (c) Fredrik Lundh 1997-2004.
#
# See the README file for information on usage and redistribution.
#
from __future__ import annotations

import re
from io import BytesIO
from typing import IO


class GimpPaletteFile:
    """File handler for GIMP's palette format."""

    rawmode = "RGB"

    def _read(self, fp: IO[bytes], limit: bool = True) -> None:
        if not fp.readline().startswith(b"GIMP Palette"):
            msg = "not a GIMP palette file"
            raise SyntaxError(msg)

        palette: list[int] = []
        i = 0
        while True:
            if limit and i == 256 + 3:
                break

            i += 1
            s = fp.readline()
            if not s:
                break

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

            v = s.split(maxsplit=3)
            if len(v) < 3:
                msg = "bad palette entry"
                raise ValueError(msg)

            palette += (int(v[i]) for i in range(3))
            if limit and len(palette) == 768:
                break

        self.palette = bytes(palette)

    def __init__(self, fp: IO[bytes]) -> None:
        self._read(fp)

    @classmethod
    def frombytes(cls, data: bytes) -> GimpPaletteFile:
        self = cls.__new__(cls)
        self._read(BytesIO(data), False)
        return self

    def getpalette(self) -> tuple[bytes, str]:
        return self.palette, self.rawmode