Python 3.x PIL图像保存和旋转

qmelpv7a  于 2022-12-15  发布在  Python
关注(0)|答案(1)|浏览(173)

我的代码是:

from PIL.ExifTags import *
from PIL import Image
import sys
import os
import glob
import time

image_fileList = []
mainFolder = 'C:' + chr(92) + 'Users' + chr(92) + 'aa\Desktop\ToDigitalFrame\To select from'
folderList = [x[0] for x in os.walk(mainFolder)]
print(folderList)

def saveImage(imgName):
    imgName.save('rotated.jpg')

for folder in folderList:
    print(folder)
    for image_file in glob.glob(folder + '/*.jpg'):
        print(image_file)
        if not os.path.isfile(image_file):
            sys.exit("%s is not a valid image file!")

        img = Image.open(image_file)
        info = img._getexif()
        exif_data = {}
        if info:
            for (tag, value) in info.items():
                decoded = TAGS.get(tag, tag)
                if type(value) is bytes:
                    try:
                        exif_data[decoded] = value.decode("utf-8")
                    except:
                        pass
                else:
                    exif_data[decoded] = value
        else:
            sys.exit("No EXIF data found!")

        print(exif_data)

        if exif_data['Orientation'] == 6:
            im = Image.open(image_file)
            im.rotate(280, expand=True).show()
            # saveImage(im)
            im.save('rotated.jpg')
        elif exif_data['Orientation'] == 3:
            im = Image.open(image_file)
            im.rotate(180, expand=True).show()
            saveImage(im)
        elif exif_data['Orientation'] == 8:
            im = Image.open(image_file)
            im.rotate(90, expand=True).show()
            saveImage(im)
        elif exif_data['Orientation'] == 4:
            im = Image.open(image_file)
            im.rotate(270, expand=True).show()
            saveImage(im)

在我的图片,方向大多是6(6 =旋转90 CW)我想旋转他们270度。所以,我的预览是:

和我保存的输出文件等于默认文件:

所以,它并没有保存旋转后的图片,这段代码只是把原始图片再保存一次,我想保存旋转后的图片,我知道我把图片旋转了280度,而不是270度,但是,只是为了说明它并没有保存它。

bqf10yzr

bqf10yzr1#

rotate()返回该图像的旋转副本。
那么试试看:

im = Image.open(image_file)
  im=im.rotate(270, expand=True)
  im.show()
  im.save('rotated.jpg')

参见文档:https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.rotate

相关问题