You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PIL调整图片大小并保持原始方向的方法

解决JPG图片缩放后方向异常的问题

问题出在JPG图片的EXIF方向元数据上:很多手机或相机拍摄的纵向照片,实际存储的像素数据是横向的,仅通过EXIF标签标记需要旋转的方向。PIL的Image.open()默认不会自动应用这个旋转,导致你基于原始像素数据缩放后,图片显示方向与原图不符。

修复方法

使用Pillow的ImageOps.exif_transpose()方法,它会自动读取EXIF方向信息并调整图片像素数据至正确方向,之后再进行缩放操作即可保持方向一致。

修改后的完整脚本

from PIL import Image, ImageOps  # 新增ImageOps导入
import os, sys

final_size = 1200;

def resize_aspect_fit(dir):
    dirs = os.listdir(dir)
    print("resizing " + dir)
    for item in dirs:
         if item == 'resize.py':
             continue
         if item == 'resized':
             continue
         if os.path.isdir(dir + item):
             resize_aspect_fit(dir + item + "\\")
         elif os.path.isfile(dir + item):
             print("processing " + item)
             im = Image.open(dir + item)
             # 新增:根据EXIF方向调整图片
             im = ImageOps.exif_transpose(im)
             f, e = os.path.splitext(item)
             size = im.size
             ratio = float(final_size) / max(size)
             new_image_size = tuple([int(x*ratio) for x in size])
             im = im.resize(new_image_size, Image.ANTIALIAS)
             if not os.path.isdir("resized\\" + dir):
                 os.makedirs("resized\\" + dir)             
             im.save("resized\\" + dir + f + '_%ipix.jpg'%final_size, 'JPEG', quality=90)
         else:
             print(dir + item + " not a file")

resize_aspect_fit(".\\")

注意事项

  • 该方法需要Pillow 6.0.0及以上版本,若版本过低需先升级:pip install --upgrade pillow
  • 调整后的图片会将EXIF方向对应的旋转/翻转直接应用到像素数据中,因此保存后的图片无需依赖EXIF标签也能正确显示方向。

内容的提问来源于stack exchange,提问作者Amos Egel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 05:00:24