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

Python Pillow转手机图片为PDF时竖图自动横置问题求助

解决Pillow转换手机图片到PDF时方向错误的问题

问题根源

手机拍摄的JPG/PNG图片会在EXIF元数据中记录拍摄方向(Orientation标签),但Pillow的Image.open()默认不会自动应用这个旋转信息,导致竖版图片在生成PDF时被错误显示为横版。

修正后的代码

以下代码会读取图片的EXIF方向信息,自动纠正图片方向,同时按文件名排序(匹配你的日期命名规则,保证时间顺序),最终生成单份PDF:

import os
from PIL import Image, ExifTags

current_dir = os.getcwd()
pdf_filename = 'Auskundung.pdf'
pdf_path = os.path.join(current_dir, pdf_filename)

# 筛选图片文件并按文件名排序(匹配你的日期命名规则,保证时间顺序)
image_extensions = ('.jpg', '.jpeg', '.png')
image_filenames = sorted(
    [f for f in os.listdir(current_dir) if f.lower().endswith(image_extensions)]
)

processed_images = []

for filename in image_filenames:
    img_path = os.path.join(current_dir, filename)
    with Image.open(img_path) as img:
        # 读取并应用EXIF方向信息
        try:
            exif_data = img._getexif()
            if exif_data:
                orientation = exif_data.get(ExifTags.Base.Orientation)
                # 根据EXIF的Orientation值旋转图片
                if orientation == 3:
                    img = img.rotate(180, expand=True)
                elif orientation == 6:
                    img = img.rotate(270, expand=True)
                elif orientation == 8:
                    img = img.rotate(90, expand=True)
        except (AttributeError, KeyError, IndexError):
            # 无EXIF信息或Orientation标签时跳过处理
            pass

        # 将带Alpha通道的图片转为RGB(PDF不支持透明通道)
        if img.mode in ('RGBA', 'P'):
            img = img.convert('RGB')

        processed_images.append(img)

# 生成PDF
if processed_images:
    processed_images[0].save(
        pdf_path,
        "PDF",
        resolution=300.0,
        save_all=True,
        append_images=processed_images[1:]
    )
    print("PDF已生成!")
else:
    print("未找到任何图片文件!")

关键说明

  1. EXIF方向处理:
    • 手机拍摄的图片通常用Orientation值记录方向:
      • 3:需要旋转180度
      • 6:需要顺时针旋转90度(竖拍图片常见)
      • 8:需要逆时针旋转90度
    • 代码会自动读取该值并应用正确旋转,保证图片和拍摄时的方向一致。
  2. 文件名排序:
    • 使用sorted()对图片文件名排序,匹配你按日期命名的规则,确保PDF中图片按时间顺序排列。
  3. 格式兼容:
    • 将PNG等带透明通道的图片转为RGB模式,避免PDF保存失败。

原代码问题分析

  • 第一段代码:未处理EXIF方向信息,直接读取图片的原始像素数据(未应用旋转),导致竖图显示错误。
  • 第二段代码:通过宽高判断旋转方向,逻辑不准确——EXIF记录的方向才是真实拍摄方向,仅靠宽高判断可能出现误判。

内容的提问来源于stack exchange,提问作者Christoph Mesenhuber

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 12:15:41