簡體   English   中英

Django上傳后旋轉iPhone圖像

[英]Django rotates iphone image after upload

我在一個圖片網站上工作,我希望用戶能夠上傳肖像或風景照片。 最大寬度應為1250像素,但如果是縱向模式,則最大高度可以為1667像素。 當我縱向上傳照片時,它們會向左旋轉90度。 有沒有辦法使用枕頭來確保照片保持正確的方向?

這是我的代碼:

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()

用戶在手機移動時能夠從手機上傳照片很重要,因此正確的方向非常重要。 我在這里能做什么?

您可以嘗試使用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