Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3.x PIL image saving and rotating

My code is:

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)

In my pictures, the Orientation is mostly 6 (6 = Rotate 90 CW)I want to rotate them with 270 degrees. So, my preview is:preview And my saved output file is equal with the default file:savedFile

So, it doesn't really save the rotated picture, this code just saves the original picture one more time. I want to save the rotated picture! I know I'm rotating the picture with 280 degrees instead of 270 degrees but, just to show it doesn't save it.

like image 249
I'm the man. Avatar asked May 18 '26 15:05

I'm the man.


1 Answers

the Image.rotate() returns a rotated copy of this image.

so how about try:

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

see the docs:https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.rotate

like image 72
Sinon Avatar answered May 21 '26 05:05

Sinon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!