converting tiff to jpeg in python

喜欢而已 提交于 2019-12-03 11:30:14

问题


Can anyone help me to read .tiff image and convert into jpeg format?

from PIL import Image
im = Image.open('test.tiff')
im.save('test.jpeg')

The above code was not working.


回答1:


I have successfully solved the issue. I posted the code to read the tiff files in a folder and convert into jpeg automatically.

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, e:
                    print e



回答2:


import os, sys
from PIL import Image

I tried to save directly to jpeg but the error indicated that the mode was P and uncompatible with JPEG format so you have to convert it to RGB mode as follow.

for infile in os.listdir("./"):
    print "file : " + infile
    if infile[-3:] == "tif" or infile[-3:] == "bmp" :
       # print "is tif or bmp"
       outfile = infile[:-3] + "jpeg"
       im = Image.open(infile)
       print "new filename : " + outfile
       out = im.convert("RGB")
       out.save(outfile, "JPEG", quality=90)


来源:https://stackoverflow.com/questions/28870504/converting-tiff-to-jpeg-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!