Python-docx: Insert PIL.Image into document

Created on 8 Jul 2019  路  1Comment  路  Source: python-openxml/python-docx

Can there be an option to use a PIL.Image object when using the .add_picture function? This would be useful for things like editing an image using PIL before inserting the image into a document or grabbing an image from the internet without having to save it first.

Most helpful comment

I'd be disinclined to add something like that. It's pretty application-specific and the image _must_ be converted to a PNG, JPG, etc. "file" before saving in PowerPoint anyway, since that's the format PowerPoint understands.

There's no need to save it to disk, by the way, an io.BytesIO object works fine wherever python-docx otherwise takes a file path for an image.

A short function like this in your application code would provide a handy wrapper:

import io

def image2file(image):
    """Return `image` as PNG file-like object."""
    image_file = io.BytesIO()
    image.save(image_file, format="PNG")
    return image_file

...

document.add_picture(image2file(image))

>All comments

I'd be disinclined to add something like that. It's pretty application-specific and the image _must_ be converted to a PNG, JPG, etc. "file" before saving in PowerPoint anyway, since that's the format PowerPoint understands.

There's no need to save it to disk, by the way, an io.BytesIO object works fine wherever python-docx otherwise takes a file path for an image.

A short function like this in your application code would provide a handy wrapper:

import io

def image2file(image):
    """Return `image` as PNG file-like object."""
    image_file = io.BytesIO()
    image.save(image_file, format="PNG")
    return image_file

...

document.add_picture(image2file(image))
Was this page helpful?
0 / 5 - 0 ratings

Related issues

madphysicist picture madphysicist  路  3Comments

evbo picture evbo  路  3Comments

avvRobertoAlma picture avvRobertoAlma  路  7Comments

chcourses picture chcourses  路  3Comments

floatc picture floatc  路  4Comments