Python Guide - Scrubbing Image Exif Data

This python program takes an existing image and creates a new image without the EXIF data, effectively stripping all the information off. Works on all image types tested and doesn't significantly reduce image quality as far as I can tell.

A step by step guide is commented throughout the code below.

The example image was taken with a DJI drone as noted by the file name.

#######Step 1: Imports
#pip install pillow https://pypi.org/project/Pillow/2.2.1/
#And use the tkinter module that comes standard with your python install

#use PIL as a pointer to the pillow module because it is a fork of the now dead PIL module)
from PIL import Image, ExifTags

#use filedialog to select the image file using the OS directory instead of manually typing in the location
from tkinter import filedialog

#######Step 2: the main function
def main():
# open the file dialog and choose the image to get the location string
img = filedialog.askopenfilename()

#grab the image name by stripping everything else
a = str(img.rsplit('/',1)[1])
a = a.rsplit('.',1)[0]
print(a)

#we open the image with PIL
img = Image.open(img)

#use a try-except block to error handle in case there is no exif data
try:

#with the _getexif().items() we first try to obtain a dictionary of all the exif data on the image
exifData = { ExifTags.TAGS[k]: v for k, v in img._getexif().items() if k in ExifTags.TAGS }
#if there is none we exit this block and move to the exception

#we grab the image data and set it to an object
imgData = list(img.getdata())

#create a new image using the same mode and size of the original image
image_without_exifData = Image.new(img.mode, img.size)

#place back the pixel data into the new image
image_without_exifData.putdata(imgData)

#initiate the orientation object
for orientation in ExifTags.TAGS.keys():
if ExifTags.TAGS[orientation]=='Orientation':
break

#PIL does not copy metadata when saving a new image
#So first read the metadata, grab the orientation, and set up the new image with
#the correct orientation
#this means we are adding our own metadata to the new image
rotate=dict(img._getexif().items())
if rotate[orientation] == 3:
img=img.rotate(180, expand=True)
elif rotate[orientation] == 6:
img=img.rotate(270, expand=True)
elif rotate[orientation] == 8:
img=img.rotate(90, expand=True)
else:
pass


#clean up name and final save
#this will always save in the directory your python program is in
img.save(u"scrubbed_{}".format(a+'.jpg'))

except Exception as e:
#print the error
print(e)

return

#######Step 3: making main() automatically run on 'python program.py' in command window
if __name__=="__main__":
main()