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

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

Copy link
Copy Markdown
Author

script to reproduce/test the behavior:

fromdocximportDocumentfromPILimportImage, ImageDraw# Draw a black arrow shaft and arrowheadimg=Image.new("RGB", (300, 400), "white")
d=ImageDraw.Draw(img)
cx, shaft_top, shaft_h=150, 50, 200d.rectangle([(145, shaft_top), (155, shaft_top+shaft_h)], fill="black")
d.polygon([(150, 30), (130, 70), (170, 70)], fill="black")
# Save the imageimg.save("arrow.jpg")
# Create a document and add the imagedocument=Document()
document.add_picture("arrow.jpg")
document.save("arrow_up.docx")
# Rotate the image only by changing the EXIF orientation, then save itimg=Image.open("arrow.jpg")
exif=img.getexif()
exif[0x0112] =6img.save("arrow_rotated.jpg", exif=exif)
# Create a document and add the rotated imagedocument=Document()
document.add_picture("arrow_rotated.jpg")
document.save("arrow_rotated.docx")

Sign up for freeto 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

@TheZ3ro