使用PIL压缩图像而不更改图像方向

时间:2018-11-24 15:46:12

标签: python-3.x python-imaging-library

我想找到一种压缩图像并使其保持相同方向的方法。 我的代码:

def save(self, **kwargs):
    super(Post, self).save()
    if self.picture:
        mywidth = 1100
        image = Image.open(self.picture)
        wpercent = (mywidth / float(image.size[0]))
        hsize = int((float(image.size[1]) * float(wpercent)))
        image = image.resize((mywidth, hsize), Image.ANTIALIAS)
        image.save(self.picture.path)

即使我仅使用此位:

image = Image.open(self.picture)

然后不做任何操作将其保存

image.save(self.picture.path)

它仍然使我的照片的方向改变了...

1 个答案:

答案 0 :(得分:0)

我怀疑您遇到的问题与PIL thumbnail is rotating my image?

PIL没有像这样旋转图像。图像文件上有一个标志,指示枕头正在读取但未保存到新文件的图像方向。

所以我会尝试-

from PIL import Image, ExifTags

def save(self, **kwargs):
    super(Post, self).save()
    if self.picture:
        mywidth = 1100
        image = Image.open(self.picture)

        if hasattr(image, '_getexif'):
            exif = image._getexif()
            if exif:
                for tag, label in ExifTags.TAGS.items():
                    if label == 'Orientation':
                        orientation = tag
                        break
                if orientation in exif:
                    if exif[orientation] == 3:
                        image = image.rotate(180, expand=True)
                    elif exif[orientation] == 6:
                        image = image.rotate(270, expand=True)
                    elif exif[orientation] == 8:
                        image = image.rotate(90, expand=True)

        wpercent = (mywidth / float(image.size[0]))
        hsize = int((float(image.size[1]) * float(wpercent)))
        image = image.resize((mywidth, hsize), Image.ANTIALIAS)
        image.save(self.picture.path)