'Given a set of images writes the bytes to the specified stream.'

def _write_gif(self, filename, duration=0.1, loops=0, dither=1):

    frames = 0
    previous = None
    fp = open(filename, 'wb')
    if (not PIL_ENABLED):
        logger.warning('Need    PIL    to    write    animated    gif    files.')
        return
    converted = []
    for img in self:
        if (not isinstance(img, pil.Image)):
            pil_img = img.getPIL()
        else:
            pil_img = img
        converted.append((pil_img.convert('P', dither=dither), img._get_header_anim()))
    try:
        for (img, header_anim) in converted:
            if (not previous):
                palette = getheader(img)[1]
                data = getdata(img)
                (imdes, data) = (data[0], data[1:])
                header = header_anim
                appext = self._get_app_ext(loops)
                graphext = self._get_graphics_control_ext(duration)
                fp.write(header)
                fp.write(palette)
                fp.write(appext)
                fp.write(graphext)
                fp.write(imdes)
                for d in data:
                    fp.write(d)
            else:
                data = getdata(img)
                (imdes, data) = (data[0], data[1:])
                graphext = self._get_graphics_control_ext(duration)
                fp.write(graphext)
                fp.write(imdes)
                for d in data:
                    fp.write(d)
            previous = img.copy()
            frames = (frames + 1)
        fp.write(';')
    finally:
        fp.close()
        return frames
