2
# Python Imaging Library
5
# stuff to read (and render) GIMP gradient files
10
# Copyright (c) Secret Labs AB 1997.
11
# Copyright (c) Fredrik Lundh 1997.
13
# See the README file for information on usage and redistribution.
16
from math import pi, log, sin, sqrt
19
# --------------------------------------------------------------------
20
# Stuff to translate curve segments to palette values (derived from
21
# the corresponding code in GIMP, written by Federico Mena Quintero.
22
# See the GIMP distribution for more information.)
27
def linear(middle, pos):
32
return 0.5 * pos / middle
39
return 0.5 + 0.5 * pos / middle
41
def curved(middle, pos):
42
return pos ** (log(0.5) / log(max(middle, EPSILON)))
44
def sine(middle, pos):
45
return (sin((-pi / 2.0) + pi * linear(middle, pos)) + 1.0) / 2.0
47
def sphere_increasing(middle, pos):
48
return sqrt(1.0 - (linear(middle, pos) - 1.0) ** 2)
50
def sphere_decreasing(middle, pos):
51
return 1.0 - sqrt(1.0 - linear(middle, pos) ** 2)
53
SEGMENTS = [ linear, curved, sine, sphere_increasing, sphere_decreasing ]
59
def getpalette(self, entries = 256):
64
x0, x1, xm, rgb0, rgb1, segment = self.gradient[ix]
66
for i in range(entries):
68
x = i / float(entries-1)
72
x0, x1, xm, rgb0, rgb1, segment = self.gradient[ix]
77
scale = segment(0.5, 0.5)
79
scale = segment((xm - x0) / w, (x - x0) / w)
82
r = chr(int(255 * ((rgb1[0] - rgb0[0]) * scale + rgb0[0]) + 0.5))
83
g = chr(int(255 * ((rgb1[1] - rgb0[1]) * scale + rgb0[1]) + 0.5))
84
b = chr(int(255 * ((rgb1[2] - rgb0[2]) * scale + rgb0[2]) + 0.5))
85
a = chr(int(255 * ((rgb1[3] - rgb0[3]) * scale + rgb0[3]) + 0.5))
88
palette.append(r + g + b + a)
90
return string.join(palette, ""), "RGBA"
93
# File handler for GIMP's gradient format.
95
class GimpGradientFile(GradientFile):
97
def __init__(self, fp):
99
if fp.readline()[:13] != "GIMP Gradient":
100
raise SyntaxError, "not a GIMP gradient file"
102
count = int(fp.readline())
106
for i in range(count):
108
s = string.split(fp.readline())
109
w = map(float, s[:11])
116
segment = SEGMENTS[int(s[11])]
120
raise IOError, "cannot handle HSV colour space"
122
gradient.append((x0, x1, xm, rgb0, rgb1, segment))
124
self.gradient = gradient