使用PIL压缩图像时不改变图像方向

3

我希望找到一种压缩图像并保持相同方向的方法。

我的代码:

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)

它仍然给我带来了方向改变的图片...

2个回答

3

我猜测你遇到了与PIL缩略图旋转我的图片?相同的问题。

PIL并没有直接旋转图片。图片文件有一个标记,记录了图片的方向,Pillow读取了这个标记,但没有保存到新文件中。

因此,我建议你尝试 -

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)

2

@radarhere提到的方法很好,但是自从Pillow 6.x以来,不需要进行复杂的手动方向调整,只需使用exif_transpose方法即可:https://pillow.readthedocs.io/en/latest/_modules/PIL/ImageOps.html#exif_transpose

该方法根据EXIF方向信息对图像执行变换(旋转、转置等),然后通过删除该部分和更多内容(如果需要),但基本上保留其余的EXIF数据来调整EXIF数据。

这样,代码就非常简单了(它可以处理比3、6、8更多的方向类型):

from PIL import Image, ImageOps
image = Image.open(self.picture)
fixed_image = ImageOps.exif_transpose(image)

我认为在此之后进行调整大小将会删除EXIF信息,因为尺寸发生了变化,但此时图像已经具有正确的方向而没有EXIF元数据,所以一切都很好。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接