Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django rotates iphone image after upload

I'm working on a photo website where I want the user to be able to upload a portrait or landscape oriented photo. The maximum width should be 1250px, but the maximum height could be 1667px if it's in portrait mode. When I upload photos in portrait orientation, they show up rotated 90 degrees to the left. Is there a way using Pillow to make sure the photo stays in the correct orientation?

This is my code:

class Result(models.Model):
    result01        = models.FileField(upload_to=get_upload_file_name, null=True, blank=True)
    result01thumb   = models.FileField(upload_to=get_upload_file_name, null=True, blank=True)

    def save(self):
        super(Result, self).save()
        if self.result01:
            size = 1667, 1250
            image = Image.open(self.result01)
            image.thumbnail(size, Image.ANTIALIAS)
            fh = storage.open(self.result01.name, "w")
            format = 'png'
            image.save(fh, format)
            fh.close()

It's important that users be able to upload photos from their phones while they're mobile, so the correct orientation is really important. Is there anything I can do here?

like image 953
Jason Boyce Avatar asked May 08 '15 14:05

Jason Boyce


People also ask

How do I get my iPhone 11 pictures to turn sideways?

Swipe down from the top right-hand corner of your screen to open Control Centre. Tap the Portrait Orientation Lock button to make sure it's turned off. Turn your iPhone sideways.

How do you slightly rotate a picture?

Rotate an image in 2 steps. 1. With your image open in Photoshop, go to Image > Image Rotation. 2. Select from the image rotation options — 90 degrees clockwise, 90 degrees counterclockwise, or 180 degrees.


1 Answers

You can try something like this to resize and auto-rotate (based on exif information) an image using Pillow.

def image_resize_and_autorotate(infile, outfile):
    with Image.open(infile) as image:
        file_format = image.format
        exif = image._getexif()

        image.thumbnail((1667, 1250), resample=Image.ANTIALIAS)

        # if image has exif data about orientation, let's rotate it
        orientation_key = 274 # cf ExifTags
        if exif and orientation_key in exif:
            orientation = exif[orientation_key]

            rotate_values = {
                3: Image.ROTATE_180,
                6: Image.ROTATE_270,
                8: Image.ROTATE_90
            }

            if orientation in rotate_values:
                image = image.transpose(rotate_values[orientation])

        image.save(outfile, file_format)
like image 174
Augusto Destrero Avatar answered Oct 28 '22 00:10

Augusto Destrero