Skip to content

Add support for image orientation - #1575

Open
TheZ3ro wants to merge 1 commit into
python-openxml:masterfrom
TheZ3ro:image-rotation
Open

Add support for image orientation#1575
TheZ3ro wants to merge 1 commit into
python-openxml:masterfrom
TheZ3ro:image-rotation

Conversation

@TheZ3ro

@TheZ3ro TheZ3ro commented Aug 4, 2026

Copy link
Copy Markdown

Fixes #540

Modern image formats (PNG, JPEG, Tiff, etc) embed the orientation in Exif metadata.
When rotating or displaying an image, software like Word, PowerPoint, macOS Preview, Android Google Photo, etc do not rotate the actual pixel data but instead change the orientation metadata integer (https://exifstrip.com/guides/orientation-tag-explained)

This is governed in OpenXML with the a:xfrm (transform) tag. This tag can contain the rot, flipV, and flipH attributes. By mapping the 1-8 orientation values to the respective rot and flip attributes it's possible to display images that were rotated by merely changing the Exif metadata with the correct orientation.

This PR add support for image orientation.

By default it gets orientation from Exif metadata. If orientation metadata is not available it falls back to "Normal" orientation (like now, defined by raw pixel data).

It is also possible to force a given orientation programmatically by:

document.add_picture(path_to_picture, width=Inches(3), orientation=EXIF_ORIENTATION.ROTATE_90))
last_paragraph = document.paragraphs[-1]
last_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER

… from Exif data then fallback to normal orientation.
@TheZ3ro

TheZ3ro commented Aug 4, 2026

Copy link
Copy Markdown
Author

script to reproduce/test the behavior:

from docx import Document
from PIL import Image, ImageDraw

# Draw a black arrow shaft and arrowhead
img = Image.new("RGB", (300, 400), "white")
d = ImageDraw.Draw(img)
cx, shaft_top, shaft_h = 150, 50, 200
d.rectangle([(145, shaft_top), (155, shaft_top + shaft_h)], fill="black")
d.polygon([(150, 30), (130, 70), (170, 70)], fill="black")
# Save the image
img.save("arrow.jpg")

# Create a document and add the image
document = Document()
document.add_picture("arrow.jpg")
document.save("arrow_up.docx")

# Rotate the image only by changing the EXIF orientation, then save it
img = Image.open("arrow.jpg")
exif = img.getexif()
exif[0x0112] = 6
img.save("arrow_rotated.jpg", exif=exif)

# Create a document and add the rotated image
document = Document()
document.add_picture("arrow_rotated.jpg")
document.save("arrow_rotated.docx")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Problem with rotation when adding images

1 participant