'Rewrites the image to reorder the palette.
:param dest_map: A list of indexes into the original palette.
e.g. [1,0] would swap a two item palette, and list(range(255))
is the identity transform.
:param source_palette: Bytes or None.
:returns:  An :py:class:`~PIL.Image.Image` object.'

def remap_palette(self, dest_map, source_palette=None):

    from . import ImagePalette
    if (self.mode not in ('L', 'P')):
        raise ValueError('illegal    image    mode')
    if (source_palette is None):
        if (self.mode == 'P'):
            source_palette = self.im.getpalette('RGB')[:768]
        else:
            source_palette = bytearray(((i // 3) for i in range(768)))
    palette_bytes = ''
    new_positions = ([0] * 256)
    for (i, oldPosition) in enumerate(dest_map):
        palette_bytes += source_palette[(oldPosition * 3):((oldPosition * 3) + 3)]
        new_positions[oldPosition] = i
    mapping_palette = bytearray(new_positions)
    m_im = self.copy()
    m_im.mode = 'P'
    m_im.palette = ImagePalette.ImagePalette('RGB', palette=(mapping_palette * 3), size=768)
    m_im.im.putpalette(*m_im.palette.getdata())
    m_im = m_im.convert('L')
    new_palette_bytes = (palette_bytes + ((768 - len(palette_bytes)) * '\x00'))
    m_im.putpalette(new_palette_bytes)
    m_im.palette = ImagePalette.ImagePalette('RGB', palette=palette_bytes, size=len(palette_bytes))
    return m_im
