【问题标题】:Python 3.x PIL image saving and rotatingPython 3.x PIL 图像保存和旋转
【发布时间】:2019-12-25 08:57:56
【问题描述】:

我的代码是:

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

【问题讨论】:

  • 这里请注意,使用im = ImageOps.exif_transpose(im)(带有导入from PIL import Image, ImageOps)比所有if/else逻辑要容易得多,并且会从exif读取方向并为您旋转。

标签: python-3.x rotation save python-imaging-library exif


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-27
    • 2016-02-02
    • 2019-07-14
    相关资源
    最近更新 更多