Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/PIL/GimpPaletteFile.py: 29%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

45 statements  

1# 

2# Python Imaging Library 

3# $Id$ 

4# 

5# stuff to read GIMP palette files 

6# 

7# History: 

8# 1997-08-23 fl Created 

9# 2004-09-07 fl Support GIMP 2.0 palette files. 

10# 

11# Copyright (c) Secret Labs AB 1997-2004. All rights reserved. 

12# Copyright (c) Fredrik Lundh 1997-2004. 

13# 

14# See the README file for information on usage and redistribution. 

15# 

16from __future__ import annotations 

17 

18__lazy_modules__ = {"io", "re"} 

19 

20import re 

21from io import BytesIO 

22 

23TYPE_CHECKING = False 

24if TYPE_CHECKING: 

25 from typing import IO, Self 

26 

27 

28class GimpPaletteFile: 

29 """File handler for GIMP's palette format.""" 

30 

31 rawmode = "RGB" 

32 

33 def _read(self, fp: IO[bytes], limit: bool = True) -> None: 

34 if not fp.readline().startswith(b"GIMP Palette"): 

35 msg = "not a GIMP palette file" 

36 raise SyntaxError(msg) 

37 

38 palette: list[int] = [] 

39 i = 0 

40 while True: 

41 if limit and i == 256 + 3: 

42 break 

43 

44 i += 1 

45 s = fp.readline() 

46 if not s: 

47 break 

48 

49 # skip fields and comment lines 

50 if re.match(rb"\w+:|#", s): 

51 continue 

52 if limit and len(s) > 100: 

53 msg = "bad palette file" 

54 raise SyntaxError(msg) 

55 

56 v = s.split(maxsplit=3) 

57 if len(v) < 3: 

58 msg = "bad palette entry" 

59 raise ValueError(msg) 

60 

61 palette += (int(v[i]) for i in range(3)) 

62 if limit and len(palette) == 768: 

63 break 

64 

65 self.palette = bytes(palette) 

66 

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

68 self._read(fp) 

69 

70 @classmethod 

71 def frombytes(cls, data: bytes) -> Self: 

72 self = cls.__new__(cls) 

73 self._read(BytesIO(data), False) 

74 return self 

75 

76 def getpalette(self) -> tuple[bytes, str]: 

77 return self.palette, self.rawmode