Repository navigation
Problem with rotation when adding images #540
Description
Activity
What file-type images are they? JPG, or PNG perhaps? Also, how do they open up when you use a photo viewer/app on your computer (not a phone or tablet)?
If you insert them into PowerPoint by hand (not using python-pptx), do they appear with the rotation you expect?
The answer to the "what does PowerPoint do?" question will be interesting, but I think in any case, you're going to need to pre-process your images to "auto-rotate" them based on the EXIF-orientation value, if present. There's a stackoverflow question that seems to have a solution using PIL here:
https://stackoverflow.com/questions/13872331/rotating-an-image-with-orientation-specified-in-exif-using-python-without-pil-inLet us know how you go. I'm sure others will find their way here with a similar problem.
yes, i've find myself in totally same situation. to the question "what does PowerPoint do?": it's portrait when i insert by hand, but when by python-pptx, it's landscape. copilot tell me it's because python-pptx and PowerPoint do not respect EXIF orientation—they insert the raw pixel data as-is.
apparently the answer to the question "what does PowerPoint do?" is that it interprets the Exif metadata of the image and set the
a:xfrmrot,flipV, andflipHattributes.I've opened a PR to implement this behavior here: #1575
This can be reproduced with the following script:
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")
This is documented:
I'm adding some images to a document and some of them rotate itself. The picture should be placed as portrait and it rotates automatically to landscape.
Here it is the code I'm using:
It works on a for loop, so lots of images can be added.