0

I wrote this short program to convert JPEG files in a folder into thumbnails.

import os
import glob
from PIL import Image
from PIL import ExifTags

size = (800,800)

for infile in glob.glob("c:/Users/ascklee/Desktop/PIL_test/*.jpg"):
    file, ext = os.path.splitext(infile)
    im = Image.open(infile)

    exif = {
        ExifTags.TAGS[k]: v
        for k, v in im._getexif().items()
        if k in ExifTags.TAGS
    }

    for i in exif:
        print (i, ":", exif[i])

    if exif['Orientation'] == 3:
        image=im.rotate(180, expand=True)
    elif exif['Orientation'] == 6:
        image=im.rotate(270, expand=True)
    elif exif['Orientation'] == 8:
        image=im.rotate(90, expand=True)

    image.thumbnail(size)
    image.save(file + "_TN" + ".jpg", "JPEG")

It is really strange because the first time, the program runs fine. It fails after the first image if I run it again, without first deleting the thumbnails it created the first time round.

This is the error message I get:

Traceback (most recent call last):
  File "C:\Users\ascklee\AppData\Local\Programs\Python\Python37-32\Creating 
Thumbnails (orientation - 4).py", line 14, in <module>
    for k, v in im._getexif().items()
AttributeError: 'NoneType' object has no attribute 'items'

I am using IDLE 3.7.0.

Any help is greatly appreciated. Thank you.

Carlos Gonzalez
  • 858
  • 13
  • 23
ascklee
  • 43
  • 3
  • Possible duplicate of [Why is my \_getexif() returning None?](https://stackoverflow.com/questions/47021950/why-is-my-getexif-returning-none) – Mike Scotty Nov 02 '18 at 15:36

1 Answers1

0

one of the images is returning None to the im._getexif() call, it's possible it doesn't have any exif tags, you can work around this by changing your code to look like this

import os
import glob
from PIL import Image
from PIL import ExifTags

size = (800,800)

for infile in glob.glob("c:/Users/ascklee/Desktop/PIL_test/*.jpg"):
    file, ext = os.path.splitext(infile)
    im = Image.open(infile)

    try:
        exif = {
            ExifTags.TAGS[k]: v
            for k, v in im._getexif().items()
            if k in ExifTags.TAGS
         }

    except AttributeError:
        print('this image has no exif tags')
        continue

    for i in exif:
        print (i, ":", exif[i])

    if exif['Orientation'] == 3:
        image=im.rotate(180, expand=True)
    elif exif['Orientation'] == 6:
        image=im.rotate(270, expand=True)
    elif exif['Orientation'] == 8:
        image=im.rotate(90, expand=True)

    image.thumbnail(size)
    image.save(file + "_TN" + ".jpg", "JPEG")
vencaslac
  • 2,727
  • 1
  • 18
  • 29