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

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

42 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 

18import re 

19from io import BytesIO 

20from typing import IO 

21 

22 

23class GimpPaletteFile: 

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

25 

26 rawmode = "RGB" 

27 

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

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

30 msg = "not a GIMP palette file" 

31 raise SyntaxError(msg) 

32 

33 palette: list[int] = [] 

34 i = 0 

35 while True: 

36 if limit and i == 256 + 3: 

37 break 

38 

39 i += 1 

40 s = fp.readline() 

41 if not s: 

42 break 

43 

44 # skip fields and comment lines 

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

46 continue 

47 if limit and len(s) > 100: 

48 msg = "bad palette file" 

49 raise SyntaxError(msg) 

50 

51 v = s.split(maxsplit=3) 

52 if len(v) < 3: 

53 msg = "bad palette entry" 

54 raise ValueError(msg) 

55 

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

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

58 break 

59 

60 self.palette = bytes(palette) 

61 

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

63 self._read(fp) 

64 

65 @classmethod 

66 def frombytes(cls, data: bytes) -> GimpPaletteFile: 

67 self = cls.__new__(cls) 

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

69 return self 

70 

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

72 return self.palette, self.rawmode