This commit is contained in:
hugovk 2014-07-15 18:38:10 +03:00
parent 4b40839970
commit 17223001df

View File

@ -23,13 +23,13 @@ from PIL import Image, ImageColor
class ImagePalette:
"Color palette for palette mapped images"
def __init__(self, mode = "RGB", palette = None, size = 0):
def __init__(self, mode="RGB", palette=None, size=0):
self.mode = mode
self.rawmode = None # if set, palette contains raw data
self.rawmode = None # if set, palette contains raw data
self.palette = palette or list(range(256))*len(self.mode)
self.colors = {}
self.dirty = None
if ((size == 0 and len(self.mode)*256 != len(self.palette)) or
if ((size == 0 and len(self.mode)*256 != len(self.palette)) or
(size != 0 and size != len(self.palette))):
raise ValueError("wrong palette size")
@ -55,7 +55,7 @@ class ImagePalette:
return self.palette
arr = array.array("B", self.palette)
if hasattr(arr, 'tobytes'):
#py3k has a tobytes, tostring is deprecated.
# py3k has a tobytes, tostring is deprecated.
return arr.tobytes()
return arr.tostring()
@ -109,6 +109,7 @@ class ImagePalette:
fp.write("\n")
fp.close()
# --------------------------------------------------------------------
# Internal
@ -119,6 +120,7 @@ def raw(rawmode, data):
palette.dirty = 1
return palette
# --------------------------------------------------------------------
# Factories
@ -128,23 +130,27 @@ def _make_linear_lut(black, white):
for i in range(256):
lut.append(white*i//255)
else:
raise NotImplementedError # FIXME
raise NotImplementedError # FIXME
return lut
def _make_gamma_lut(exp, mode="RGB"):
lut = []
for i in range(256):
lut.append(int(((i / 255.0) ** exp) * 255.0 + 0.5))
return lut
def new(mode, data):
return Image.core.new_palette(mode, data)
def negative(mode="RGB"):
palette = list(range(256))
palette.reverse()
return ImagePalette(mode, palette * len(mode))
def random(mode="RGB"):
from random import randint
palette = []
@ -152,6 +158,7 @@ def random(mode="RGB"):
palette.append(randint(0, 255))
return ImagePalette(mode, palette)
def sepia(white="#fff0c0"):
r, g, b = ImageColor.getrgb(white)
r = _make_linear_lut(0, r)
@ -159,9 +166,11 @@ def sepia(white="#fff0c0"):
b = _make_linear_lut(0, b)
return ImagePalette("RGB", r + g + b)
def wedge(mode="RGB"):
return ImagePalette(mode, list(range(256)) * len(mode))
def load(filename):
# FIXME: supports GIMP gradients only
@ -177,8 +186,8 @@ def load(filename):
p = GimpPaletteFile.GimpPaletteFile(fp)
lut = p.getpalette()
except (SyntaxError, ValueError):
#import traceback
#traceback.print_exc()
# import traceback
# traceback.print_exc()
pass
if not lut:
@ -188,8 +197,8 @@ def load(filename):
p = GimpGradientFile.GimpGradientFile(fp)
lut = p.getpalette()
except (SyntaxError, ValueError):
#import traceback
#traceback.print_exc()
# import traceback
# traceback.print_exc()
pass
if not lut:
@ -206,4 +215,4 @@ def load(filename):
if not lut:
raise IOError("cannot load palette")
return lut # data, rawmode
return lut # data, rawmode