1 """Access to GIMP color palettes to be used within simulation/player"""
2
3 import os
4 from re import sub as regexp_replace
5
6 __author__ = "B. Henne"
7 __contact__ = "henne@dcsec.uni-hannover.de"
8 __copyright__ = "2011, DCSec, Leibniz Universitaet Hannover, Germany"
9 __license__ = "GPLv3"
10
11
13 """Represents a GIMP color palette read from file.
14
15 Colors can be accessed via their names."""
16
17 - def __init__(self, filename='Default.gpl'):
18 """Loads a GIMP palette from a palette file."""
19 f = open(os.path.abspath(filename), 'rt')
20 self.name = 'unnamed'
21 self.color = {}
22 counter = 2
23 for row in f:
24 if row.startswith('GIMP'):
25 continue
26 if row.startswith('Name: '):
27 self.name = regexp_replace(r'Name:\s+', '', row)
28 continue
29 if row.startswith('#'):
30 continue
31 splitted = regexp_replace(r'\s+', ' ', row).strip().split(' ', 3)
32 if 3 <= len(splitted) <= 4:
33 if len(splitted) == 3:
34 splitted.append('unnamed')
35 c = (int(splitted[0])/255.0, int(splitted[1])/255.0, int(splitted[2])/255.0)
36 name = splitted[3].lower()
37 if name in self.color:
38 if self.color[name] == c:
39 continue
40 else:
41 self.color['color%s' % counter] = c
42 counter += 1
43 else:
44 self.color[name] = c
45
47 """Returns full palette of colors as <r g b name> seperated by newlines."""
48 s = ''
49 for name in self.color.keys():
50 r, g, b = self.color[name]
51 s += '%.2f %.2f %.2f %s\n' % (r,g,b,name)
52 return s
53
54 - def rgb(self, colorname):
55 """Returns rgb triple of color from palette specified by its name.
56
57 First looks for exact match, then for first startswith match,
58 then for first substring match, finally raises KeyError."""
59 if colorname in self.color:
60 return self.color[colorname]
61 else:
62 for k in self.color.keys():
63 if k.startswith(colorname):
64 self.color[colorname] = self.color[k]
65 return self.color[colorname]
66 for k in self.color.keys():
67 if k.count(colorname) > 0:
68 self.color[colorname] = self.color[k]
69 return self.color[colorname]
70 raise KeyError(colorname)
71
72 - def rgba(self, colorname, alpha=1.0):
73 """Returns rgba quadruple of color from rgb palette specified by its name.
74
75 First looks for exact match, then for first startswith match,
76 then for first substring match, finally raises KeyError.
77 Alpha defaults to 1.0, if not set by user."""
78 return self.rgb(colorname) + (alpha,)
79
80
81 if __name__ == '__main__':
82 demopalette = 'Visibone.gpl'
83 democolor = 'medium faded blue'
84 demo = GimpPalette(demopalette)
85 print demo
86 print '%s (RGB) = %s' % (democolor, demo.rgb(democolor))
87 print '%s (RGBA) = %s' % (democolor, demo.rgba(democolor))
88 print '%s (RGBA), alpha:50%% = %s' % (democolor, demo.rgba(democolor, 0.5))
89