diff --git a/PIL/GifImagePlugin.py b/PIL/GifImagePlugin.py index aed525824..8882f9beb 100644 --- a/PIL/GifImagePlugin.py +++ b/PIL/GifImagePlugin.py @@ -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 diff --git a/PIL/ImagePalette.py b/PIL/ImagePalette.py index 61affdb19..d5b9d04eb 100644 --- a/PIL/ImagePalette.py +++ b/PIL/ImagePalette.py @@ -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):