python - 在 Python PIL 中保存动画 GIF 图像会导致质量损失?
问题描述
我正在尝试调整动画 GIF 的大小。
原图在这里。
我这样做是通过单独加载每一帧,将其保存为一张图片,然后调整这张图片的大小PIL.Image.resize()
并将其保存在一个列表中,然后将整个列表附加到保存的 GIF(总共 60 帧)中。查看单独保存的帧时,没有问题。但是当我查看保存的调整大小的动画 GIF 时,质量损失很大:
这里是调整大小的图像。
不知道是PIL的保存算法还是什么造成的,我只要把这个GIF保存成原画质,不要像这样有颗粒感。我测试了多种尺寸,包括原始尺寸(=因此避免了调整大小的部分),但似乎每次都会发生。
def get_frames(path=''):
import Image
from tkinter import PhotoImage
source_image = Image.open(path)
i = 0
palette = source_image.getpalette()
frames = []
try:
while 1:
source_image.putpalette(palette)
frames.append(Image.new("RGBA", source_image.size))
frames[i].paste(source_image)
i += 1
source_image.seek(i)
except EOFError:
pass
out = []
for frame_index in range(len(frames)):
frames[frame_index].save('../temp/frame{}.gif'.format(frame_index))
out.append('../temp/frame{}.gif'.format(frame_index))
return out
# This part creates 60 files (each for one frame),
# then returns the list of paths to those files
def downsize_frame(image_path='', new_width=30, new_height=30):
from PIL import Image
img = Image.open(image_path)
img = img.resize((new_width, new_height), Image.ANTIALIAS)
return img
# This returns the smaller image
frames = []
image = 'example.gif'
source = get_frames(path=image)
for loop in range(1, max_index):
from tkinter import TclError
try:
frames.append(downsize_frame(image_path=source[loop], new_width=48, new_height=48))
except IndexError:
frames.append(new_image)
new_image.save(out_name, 'gif', transparency=0, duration=100, loop=0,
append_images=frames, save_all=True, version='GIF89a')
解决方案
推荐阅读
- java - Hibernate 中的事务管理
- awk - 如何使用列操作的 AWK printf 保持算术运算的精度
- python - 名称“文件”未定义错误 - 将 pdf 转换为文本
- python - Django TruncWeek 中的错误返回
- apache-flink - 事件时间的聚合函数和处理函数
- maven - 如何将 GitHub 包注册表包添加为 Gradle 依赖项
- css - 无头 Chrome 未检测到网页的 css 和背景图像
- c# - 使用 C# 获取 Azure 服务器中的所有数据库
- java - 混合 JDK/JRE 热点/OpenJ9
- javascript - 使用 JavaScript 将最后一个文本框值附加到下一个文本框