简体   繁体   English

Django上传后旋转iPhone图像

[英]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. 最大宽度应为1250像素,但如果是纵向模式,则最大高度可以为1667像素。 When I upload photos in portrait orientation, they show up rotated 90 degrees to the left. 当我纵向上传照片时,它们会向左旋转90度。 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? 我在这里能做什么?

You can try something like this to resize and auto-rotate (based on exif information) an image using Pillow. 您可以尝试使用Pillow这样的操作来调整图像大小并自动旋转(基于exif信息)。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM