I am trying to grab an image hosted on a website(eg. imgur) and add it to a docx.
This is my initial code(this is part of a function. I've stripped it down to the relevant codes):
from PIL import Image
from urllib.request import urlopen
thisParagraph = document.sections[0].paragraphs[0]
run = thisParagraph.add_run()
# imgLink is a direct link to the image. Something like https://i.imgur.com/<name>.jpg
# online is a parsed-in boolean to determine if the image link is from an image hosting site
# or from the local machine
if (online):
imgLinkData = urlopen(imgLink )
img = Image.open(imgLinkData )
width, height = img.size
else:
img = Image.open(imgLink )
width, height = img.size
imgLinkData = imgLink
if (width > 250) or (height > 250):
if (height > width):
run.add_picture(imgLinkData, width=Cm(3), height=Cm(4) )
else:
run.add_picture(imgLinkData, width=Cm(4), height=Cm(3) )
else:
run.add_picture(imgLinkData)
For the most part, this works if imgLink is pointed to my local system(ie. the image is hosted on my PC).
But if I refer to a url link(online=True), I get various types of exceptions(in my attempt to fix it) ranging from io.UnsupportOperation
(seek) to TypeError
(string argument expected, got 'bytes'), the cause is always the run.add_picture
line.
The code, as it is now, throws the io.UnsupportOperation
exception.