无法将tiff图像转换为jpg

时间:2018-03-09 12:53:34

标签: python python-imaging-library

我正在尝试创建一个简单的脚本,将目录中的所有tiff图像转换为jpg,但是我收到了这个错误:

  

无法将RGBA模式写为JPEG

这是我的代码:

import os
from PIL import Image

yourpath = os.getcwd()
for root, dirs, files in os.walk(yourpath, topdown=False):
    for name in files:
        print(os.path.join(root, name))
        if os.path.splitext(os.path.join(root, name))[1].lower() == ".tiff":
            if os.path.isfile(os.path.splitext(os.path.join(root, name))[0] + ".jpg"):
                print ("A jpeg file already exists for %s" % name)
            # If a jpeg is *NOT* present, create one from the tiff.
            else:
                outfile = os.path.splitext(os.path.join(root, name))[0] + ".jpg"
                try:
                    im = Image.open(os.path.join(root, name))
                    print ("Generating jpeg for %s" % name)
                    im.thumbnail(im.size)
                    im.save(outfile, "JPEG", quality=100)
                except Exception as e:
                    print (e)

知道怎么解决吗?

2 个答案:

答案 0 :(得分:0)

RGBA代表"红色,绿色,蓝色,alpha",其中alpha是不透明度(允许部分透明的图像)。 JPEG不支持Alpha通道,因此您必须执行以下转换:

 im = im.convert("RGB")

我假设您的输入图像都不是灰度图像,或者如果它们不是,您也不介意将它们转换为RGB图像。否则,请在转换前检查im.mode

答案 1 :(得分:0)

有点晚了,但是可以正常工作

im.convert("RGB").save(outfile, "JPEG", quality=100)
相关问题