【问题标题】:Can't transform tiff image to jpg无法将 tiff 图像转换为 jpg
【发布时间】:2020-02-29 20:11:06
【问题描述】:

我正在尝试创建一个简单的脚本,将目录中的所有 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)

知道怎么解决吗?

【问题讨论】:

    标签: python python-imaging-library


    【解决方案1】:

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

     im = im.convert("RGB")
    

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

    【讨论】:

    • 我已经尝试过了,但它不起作用,图像没有创建
    【解决方案2】:

    有点晚了,但以下方法可行:

    im.convert("RGB").save(outfile, "JPEG", quality=100)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多