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

问题描述 投票:0回答:1

我的代码是:

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度。因此,我的预览是:preview我保存的输出文件等于默认文件:savedFile

因此,它并没有真正保存旋转后的图片,此代码只是将原始图片再保存一次。我要保存旋转的图片!我知道我将图片旋转280度而不是270度,但是只是为了显示它并不能保存。

python-3.x rotation save python-imaging-library exif
1个回答
0
投票

Image.rotate()返回此图像的旋转副本。

那么如何尝试:

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

请参阅文档:https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#PIL.Image.Image.rotate

© www.soinside.com 2019 - 2024. All rights reserved.