I would like to rotate an image using PIL before including this in a Word document using docx. I am starting off with an empty document. To avoid having to save the rotated image to disk, I make use of a stream. In other applications you need to 'reset' the stream to the starting position before using the content. However, I found that when using run.add_picture() this is not necessary, which I do not understand. Why is there no need to rewind the stream before adding the picture?
from docx import Document
from docx.shared import Inches
from io import BytesIO
from PIL import Image
document = Document('Test.docx')
temporary_storage = BytesIO()
print('Created the stream')
print('Pointer is at position: ' + str(temporary_storage.tell()))
paragraph = document.add_paragraph()
run = paragraph.add_run()
picture = Image.open('cat.png')
picture.rotate(90, expand=True).save(temporary_storage, format="png")
print('Saved picture to the stream')
print('Pointer is at position: ' + str(temporary_storage.tell()))
temporary_storage.seek(500)
print('Set pointer to position: 500')
print('Pointer is at position: ' + str(temporary_storage.tell()))
run.add_picture(temporary_storage, width=Inches(1.65), height=Inches(2.9))
document.save('Test_with_picture.docx')
The output is:
Created the stream
Pointer is at position: 0
Saved picture to the stream
Pointer is at position: 30828
Set pointer to position: 500
Pointer is at position: 500
Process finished with exit code 0
It works fine and the picture is nicely added to the document without setting the pointer back to zero or to any other value. Why is it not required to set it back to the start?