我尝试使用 Python 图像库将 gif 转换为单个图像,但它会导致奇怪的帧
输入 gif 是:
源图片 http://longcat.de/gif_example.gif
在我的第一次尝试中,我尝试将带有 Image.new 的图像转换为 RGB 图像,以 255,255,255 作为白色背景 - 就像我在互联网上找到的任何其他示例一样:
def processImage( infile ):
try:
im = Image.open( infile )
except IOError:
print "Cant load", infile
sys.exit(1)
i = 0
try:
while 1:
background = Image.new("RGB", im.size, (255, 255, 255))
background.paste(im)
background.save('foo'+str(i)+'.jpg', 'JPEG', quality=80)
i += 1
im.seek( im.tell() + 1 )
except EOFError:
pass # end of sequence
但它会导致奇怪的输出文件:
示例 #1 http://longcat.de/gif_example1.jpg
我的第二次尝试是,首先将 gif 转换为 RGBA,然后使用它的透明度蒙版,使透明部分变为白色:
def processImage( infile ):
try:
im = Image.open( infile )
except IOError:
print "Cant load", infile
sys.exit(1)
i = 0
try:
while 1:
im2 = im.convert('RGBA')
im2.load()
background = Image.new("RGB", im2.size, (255, 255, 255))
background.paste(im2, mask = im2.split()[3] )
background.save('foo'+str(i)+'.jpg', 'JPEG', quality=80)
i += 1
im.seek( im.tell() + 1 )
except EOFError:
pass # end of sequence
这导致这样的输出:
示例 #2 http://longcat.de/gif_example2.jpg
与第一次尝试相比的优势是,第一帧看起来不错但是正如你所看到的,其余的都坏了
接下来我应该尝试什么?
编辑:
我想我离解决方案更近了
示例 #3 http://longcat.de/gif_example3.png
我必须将第一张图像的调色板用于其他图像,并将其与前一帧合并(对于使用差异图像的 gif 动画)
def processImage( infile ):
try:
im = Image.open( infile )
except IOError:
print "Cant load", infile
sys.exit(1)
i = 0
size = im.size
lastframe = im.convert('RGBA')
mypalette = im.getpalette()
try:
while 1:
im2 = im.copy()
im2.putpalette( mypalette )
background = Image.new("RGB", size, (255,255,255))
background.paste( lastframe )
background.paste( im2 )
background.save('foo'+str(i)+'.png', 'PNG', quality=80)
lastframe = background
i += 1
im.seek( im.tell() + 1 )
except EOFError:
pass # end of sequence
但我其实不知道,为什么我的透明度是黑色,而不是白色即使我修改调色板(将透明度通道更改为白色)或使用透明度蒙版,背景仍然是黑色