Python:将 GIF 帧转换为 PNG

问题描述 投票:0回答:4

我对Python非常陌生,试图用它来将GIF的帧分割成PNG图像。

# Using this GIF: http://www.videogamesprites.net/FinalFantasy1/Party/Before/Fighter-Front.gif

from PIL import Image

im = Image.open('Fighter-Front.gif')
transparency = im.info['transparency'] 
im.save('test1.png', transparency=transparency)

im.seek(im.tell()+1)
transparency = im.info['transparency'] 
im.save('test2.png', transparency=transparency)

# First frame comes out perfect, second frame (test2.png) comes out black,
# but in the "right shape", i.e. 
# https://i.stack.imgur.com/5GvzC.png

这是我正在使用的图像所特有的还是我做错了什么?

谢谢!

python png python-imaging-library animated-gif
4个回答
18
投票

我不认为你做错了什么。请参阅此处的类似问题:动画 GIF 问题。似乎没有正确处理后面帧的调色板信息。以下对我有用:

def iter_frames(im):
    try:
        i= 0
        while 1:
            im.seek(i)
            imframe = im.copy()
            if i == 0: 
                palette = imframe.getpalette()
            else:
                imframe.putpalette(palette)
            yield imframe
            i += 1
    except EOFError:
        pass

for i, frame in enumerate(iter_frames(im)):
    frame.save('test%d.png' % i,**frame.info)

6
投票

我已经在这里修复了这个错误https://code.launchpad.net/~asdfghjkl-deactivatedaccount1/python-imaging/gif-fix

如果 GIF 使用本地颜色表,DSM 的答案将不起作用。


1
投票

我相信您可以完全删除透明度和 .info 部分,并将其替换为:

im.convert("RGBA")
就在每帧的 .save 之前。 只要您打算以支持 Alpha 通道的格式导出帧,就应该达到预期的效果。

from PIL import Image

im = Image.open('Fighter-Front.gif')
im.convert("RGBA")
im.save('test1.png')

im.seek(im.tell()+1)
im.convert("RGBA")
im.save('test2.png')

0
投票

嗯,DSM 的代码确实有帮助,但给我带来了一些错误,之后我对其进行了一些修改,现在它对我来说工作得很好。

错误:

Traceback (most recent call last):
  File "E:\practice codes\convertGIfToPNG\convertGIFtoPNG.py", line 20, in <module>
    for i, frame in enumerate(iter_frames(im)):
  File "E:\practice codes\convertGIfToPNG\convertGIFtoPNG.py", line 12, in iter_frames
    imframe.putpalette(palette)
  File "C:\Users\*****\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\PIL\Image.py", line 1939, in putpalette
    raise ValueError(msg)
ValueError: illegal image mode

重新定义代码:

from PIL import Image

def iter_frames(im):
    try:
        while True:
            current_frame = im.copy()
            yield current_frame
            im.seek(im.tell() + 1)
    except EOFError:
        pass

im = Image.open(r'E:\practice codes\convertGIfToPNG\Fighter-Front.gif')

frames = []
try:
    while True:
        frames.append(im.copy())
        im.seek(im.tell() + 1)
except EOFError:
    pass

for i, frame in enumerate(frames):
    frame.save(r'E:\practice codes\convertGIfToPNG\Fighter\Fighter%d.png' % i) #Fighter here is the folder followed by the sequence of Fighter<i>.png stored inside it
© www.soinside.com 2019 - 2024. All rights reserved.