Python-docx: 如何添加图片边框?

Python-docx: how to add a picture border?

我在文档的段落中有一张图片:

    document.add_picture("image.png")
    last_paragraph = document.paragraphs[-1]
    last_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER

如何使用 python-docx 库为这张图片添加 1px 的边框?

您可以使用 Python 的 PIL 库来完成所有图像编辑任务。要添加边框,

def add_border(input_image, output_image, border):
    img = Image.open(input_image)
    if isinstance(border, int) or isinstance(border, tuple):
        bimg = ImageOps.expand(img, border=border)
    else:
        raise RuntimeError('Border is not an image or tuple')
    bimg.save(output_image)

您现在可以根据需要调用该函数

    in_img = 'Demo_Image.png'
    add_border(in_img, output_image='DemoBorder.png', border=1)

这会将输出图像以 png 格式保存在您的工作目录中(jpg,如果保存为 DemoBorder.jpg)