So I have this issue that when someone uploads an image to my Django 1.9.2 server via an iPhone/Smartphone, the image appears rotated whenever it is fetched. I was wondering if there is a way to check the EXIF data if the image is rotated when the form/image is submitted, but rotate it before it is saved into the model.
I am trying this Proposed Solution in the following thread, but I am getting this error:
File "C:\Users\NAME\PycharmProjects\PROJECT\venv\lib\site-packages\PIL\Image.py", line 628, in __getattr__
raise AttributeError(name)
AttributeError: _committed
models.py
:
class ListingImage(models.model):
image = models.ImageField()
views.py
def create_listing(request):
if request.method == 'POST':
im = request.FILES.get('listing_image', '')
try:
image=Image.open(im)
if hasattr(image, '_getexif'): # only present in JPEGs
for orientation in ExifTags.TAGS.keys():
if ExifTags.TAGS[orientation]=='Orientation':
break
e = image._getexif() # returns None if no EXIF data
if e is not None:
exif=dict(e.items())
orientation = exif.get(orientation, None)
if orientation is None: return
if orientation == 3: image = image.transpose(Image.ROTATE_180)
elif orientation == 6: image = image.transpose(Image.ROTATE_270)
elif orientation == 8: image = image.transpose(Image.ROTATE_90)
except:
image = im
ListingImage.objects.create(image=image)