Beispiel #1
0
def resize_gif(im: GifImageFile, size: int = DEFAULT_EMOJI_SIZE) -> bytes:
    frames = []
    duration_info = []
    disposals = []
    # If 'loop' info is not set then loop for infinite number of times.
    loop = im.info.get("loop", 0)
    for frame_num in range(0, im.n_frames):
        im.seek(frame_num)
        new_frame = im.copy()
        new_frame.paste(im, (0, 0), im.convert("RGBA"))
        new_frame = ImageOps.pad(new_frame, (size, size), Image.ANTIALIAS)
        frames.append(new_frame)
        duration_info.append(im.info["duration"])
        disposals.append(im.disposal_method)
    out = io.BytesIO()
    frames[0].save(
        out,
        save_all=True,
        optimize=False,
        format="GIF",
        append_images=frames[1:],
        duration=duration_info,
        disposal=disposals,
        loop=loop,
    )
    return out.getvalue()
def convert_frame_to_transparent(imageObject: GifImageFile) -> Image:
    """
    https://stackoverflow.com/questions/3752476/python-pil-replace-a-single-rgba-color
    replaces #FFFFFF (white) with #00000000 (clear)
    """
    rgbaImage: Image = imageObject.convert('RGBA')

    data = np.array(rgbaImage)  # "data" is a height x width x 4 numpy array
    red, green, blue, alpha = data.T  # Temporarily unpack the bands for readability

    # Replace white with clear... (leaves alpha values alone...)
    white_areas = (red == 255) & (blue == 255) & (green == 255)
    data[...][white_areas.T] = (0, 0, 0, 0)  # Transpose back needed

    return Image.fromarray(data)
Beispiel #3
0
def resize_gif(im: GifImageFile, size: int=DEFAULT_EMOJI_SIZE) -> bytes:
    frames = []
    duration_info = []
    # If 'loop' info is not set then loop for infinite number of times.
    loop = im.info.get("loop", 0)
    for frame_num in range(0, im.n_frames):
        im.seek(frame_num)
        new_frame = Image.new("RGBA", im.size)
        new_frame.paste(im, (0, 0), im.convert("RGBA"))
        new_frame = ImageOps.fit(new_frame, (size, size), Image.ANTIALIAS)
        frames.append(new_frame)
        duration_info.append(im.info['duration'])
    out = io.BytesIO()
    frames[0].save(out, save_all=True, optimize=True,
                   format="GIF", append_images=frames[1:],
                   duration=duration_info,
                   loop=loop)
    return out.getvalue()