Skip to main content
 首页 » 编程设计

python之PIL 的 GIF 动画处理有问题还是我做错了

2025年05月04日7kerrycode

<分区>

Possible Duplicate:
Python: Converting GIF frames to PNG

我尝试使用 PIL 加载 GIF 动画的帧,但得到了有趣的结果。第一帧加载正常,但其余所有帧都包含错误数据。在我的原始图像上,它们看起来“变灰”,而在我在这里使用的测试图像中,它们看起来只是黑色。我猜这是由调色板索引直接用作每个组件的颜色值引起的。

我看到的第一帧数据似乎是正确的,而其他帧的数据是错误的。 IE。如果我在不查看第一帧的情况下寻找第二帧,则会得到该帧的正确数据。通过使用它,我可以通过重新打开每帧之间的图像并在新打开的图像中寻找下一帧来解决这个问题。

这似乎只有在我使用 im.convert() 时才会发生,即。当离开 GIF 的索引颜色模型时。即使在使用 im.copy() 时它也会被触发,所以即使我只是在第一帧上使用它,第二帧在使用 im.convert() 之后也会有错误的数据。

这是 PIL 中的错误,还是我只是做了一些非常非常错误的事情?我的解决方法是一个非常丑陋的 hack,有没有更好的方法来解决这个问题?

这是一个说明问题的片段:(它将测试图像作为 rgb.gif 写入当前工作目录)

import binascii 
import Image     
 
# Create the test image file 
path = 'rgb.gif' 
with file(path, 'wb') as f: 
        f.write(binascii.a2b_base64('R0lGODlhCAAIAKEDAAAA//8AAAD/AP///yH' 
            '/C05FVFNDQVBFMi4wAwEAAAAh+QQJZAADACwAAAAACAAIAAACC5yPiRHJvJ' 
            '5rqqYCACH5BAlkAAMALAAAAAAIAAgAAAILnI+JIsm8nmuqpgIAIfkECWQAA' 
            'wAsAAAAAAgACAAAAgucj4kAybyea6qmAgA7' 
        )) 
 
# Look at frame 0, then load frame 1 
im = Image.open(path) 
test1_frame0 = im.copy() 
im.seek(1) 
# im.convert() returns a new image but I'm using im.copy() to 
# make it clear this shouldn't affect the original image 
test1_frame1 = im.copy().convert('RGBA').tostring() 
 
# Load frame 1 without looking at frame 0 first 
im = Image.open(path) 
im.seek(1) 
test2_frame1 = im.copy().convert('RGBA').tostring() 
 
# Result is not equal, ie. just doing im.copy() on the first frame 
# alters the second frame     
print test1_frame1 == test2_frame1 

我正在使用 PIL 1.1.7。