* fix palette handling for converted gifs

* fix gif optimization
* better auto convert paramter for gif save
This commit is contained in:
David Schmidt 2013-12-04 15:07:36 +01:00 committed by wiredfool
parent cb309c9f59
commit 93a8bc9bd3
2 changed files with 11 additions and 6 deletions

View File

@ -237,7 +237,10 @@ def _save(im, fp, filename):
# convert on the fly (EXPERIMENTAL -- I'm not sure PIL
# should automatically convert images on save...)
if Image.getmodebase(im.mode) == "RGB":
imOut = im.convert("P")
palette_size = 256
if im.palette:
palette_size = len(im.palette.getdata()[1]) // 3
imOut = im.convert("P", palette=1, colors=palette_size)
rawmode = "P"
else:
imOut = im.convert("L")
@ -248,9 +251,7 @@ def _save(im, fp, filename):
palette = im.encoderinfo["palette"]
except KeyError:
palette = None
if im.palette:
# use existing if possible
palette = im.palette.getdata()[1]
im.encoderinfo["optimize"] = im.encoderinfo.get("optimize", True)
header, usedPaletteColors = getheader(imOut, palette, im.encoderinfo)
for s in header:
@ -391,6 +392,9 @@ def getheader(im, palette=None, info=None):
for i in range(len(imageBytes)):
imageBytes[i] = newPositions[imageBytes[i]]
im.frombytes(bytes(imageBytes))
newPaletteBytes = paletteBytes + (768 - len(paletteBytes)) * b'\x00'
im.putpalette(newPaletteBytes)
im.palette = ImagePalette.ImagePalette("RGB", palette = paletteBytes, size = len(paletteBytes))
if not paletteBytes:
paletteBytes = sourcePalette

View File

@ -23,13 +23,14 @@ from PIL import Image, ImageColor
class ImagePalette:
"Color palette for palette mapped images"
def __init__(self, mode = "RGB", palette = None):
def __init__(self, mode = "RGB", palette = None, size = 0):
self.mode = mode
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 len(self.mode)*256 != len(self.palette):
if ((size == 0 and len(self.mode)*256 != len(self.palette)) or
(size != 0 and size != len(self.palette))):
raise ValueError("wrong palette size")
def getdata(self):