python gif转jpg_PIL-将GIF帧转换为JPG

博主尝试使用Python的图像库将GIF转换为单个JPEG或PNG图像,遇到透明度处理和背景颜色问题。第一次尝试直接将GIF转换为RGB图像,导致输出图像异常。第二次尝试通过转换为RGBA并应用透明遮罩,虽然改善了第一帧效果,但后续帧仍然出现问题。在第三种尝试中,博主使用了前一帧的调色板,但透明度仍显示为黑色而非白色。目前寻求解决方案。
摘要由CSDN通过智能技术生成

我试着用Python图像库把gif转换成单个图像,

但这会导致奇怪的画面

输入gif是:

在我的第一次尝试中,我尝试将带有image.new的图像转换为

RGB图像,255255255为白色背景-与任何其他图像一样

我在网上找到的例子: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

但它会导致奇怪的输出文件:

我的第二个尝试是,首先转换RGBA中的gif,然后使用

它的透明遮罩,使透明片变白: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

从而产生如下输出:

与第一次尝试相比的优势是,第一帧看起来很不错

但正如你所看到的,其余的都碎了

我下一步该怎么做?

编辑:

我想我离解决方案更近了

我不得不用第一张图片的调色板来处理其他图片,

并将其与前一帧合并(对于使用

差异图像)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

但我真的不知道,为什么我的透明度是黑色的,而不是白色的

即使我修改了调色板(将透明度通道更改为白色)

或者使用透明遮罩,背景仍然是黑色的

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值