【发布时间】:2021-01-21 20:43:21
【问题描述】:
我正在研究裁剪 GIF 的解决方案。我得到了它的工作,但图像的大小增加了很多。 IE,它是 500KB 动画 GIF,但裁剪后是 8MB 动画 GIF。 我怀疑这是因为我将其转换为 RGB,然后如果 GIF 具有部分模式,则将帧与前一个帧合并。
这是我如何做到这一点的一个例子:
img = Image.open(file_path)
last_frame = img.convert('RGBA')
p = img.getpalette()
# this method analyzes image and determines if it's in partial mode.
mode = analyseImage(img)['mode']
all_frames = []
frames = ImageSequence.Iterator(img)
for frame in frames:
if not frame.getpalette():
frame.putpalette(p)
new_frame = Image.new('RGBA', img.size)
if mode == 'partial':
new_frame.paste(last_frame)
new_frame.paste(frame, (0, 0), frame.convert('RGBA'))
last_frame = new_frame.copy()
new_frame.thumbnail(size, Image.ANTIALIAS)
all_frames.append(new_frame)
return all_frames
然后我使用方法将其存储为新图像:
new_image_bytes = BytesIO()
om = all_frames[0]
om.info = img.info
om.save(new_image_bytes, format='gif', optimize=True, save_all=True, append_images=all_frames[1:], duration=img.info.get('duration'), loop=img.info.get('loop'))
这张图片是 8MB 而不是 500KB
我错过了什么明显的东西吗?
【问题讨论】:
标签: python python-imaging-library crop gif