首页 > 解决方案 > Python 3.x PIL 图像保存和旋转

问题描述

我的代码是:

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 度,但只是为了显示它并不能保存它。

标签: python-3.xrotationsavepython-imaging-libraryexif

解决方案


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


推荐阅读