【问题标题】:Django rotates iphone image after uploadDjango在上传后旋转iphone图像
【发布时间】:2015-05-08 14:33:24
【问题描述】:

我正在开发一个照片网站,我希望用户能够上传纵向或横向的照片。最大宽度应为 1250 像素,但如果处于纵向模式,则最大高度可能为 1667 像素。当我以纵向上传照片时,它们会向左旋转 90 度。有没有办法使用 Pillow 来确保照片保持正确的方向?

这是我的代码:

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

用户在移动时能够从手机上传照片非常重要,因此正确的方向非常重要。有什么我可以在这里做的吗?

【问题讨论】:

标签: ios iphone django python-imaging-library pillow


【解决方案1】:

您可以尝试使用 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-31
    • 2014-12-30
    • 2017-03-06
    • 1970-01-01
    • 2017-03-31
    • 2020-03-20
    • 2018-10-21
    相关资源
    最近更新 更多