可以使用 Python 的 docx 和 Pillow 库来实现。

首先需要安装 docx 和 Pillow 库:

pip install python-docx
pip install pillow

接下来的代码可以实现将一批图片插入到一个 word 文档中,并将它们的宽度都设置为 8cm,高度都设置为 6cm:

from docx import Document
from docx.shared import Cm
from PIL import Image

# 创建一个新的 word 文档
doc = Document()

# 图片文件名列表
image_files = ['image1.jpg', 'image2.png', 'image3.bmp']

# 遍历图片文件名列表
for image_file in image_files:
    # 打开图片文件
    image = Image.open(image_file)
    # 计算宽度和高度的缩放比例
    width_ratio = 8 / image.width
    height_ratio = 6 / image.height
    # 取缩放比例中较小的一个作为最终的缩放比例
    ratio = min(width_ratio, height_ratio)
    # 计算缩放后的宽度和高度
    width = int(image.width * ratio)
    height = int(image.height * ratio)
    # 缩放图片
    resized_image = image.resize((width, height))
    # 将缩放后的图片插入到 word 文档中
    doc.add_picture(image_file, width=Cm(8), height=Cm(6))

# 保存 word 文档
doc.save('images.docx')

在这个代码中,我们首先遍历了图片文件名列表,然后打开每个图片文件。接着,我们计算了宽度和高度的缩放比例,并取较小的一个作为最终的缩放比例。然后,我们计算了缩放后的宽度和高度,并使用 Pillow 库的 resize() 方法缩放图片。最后,我们使用 docx 库的 add_picture() 方法将缩放后的图片插入到 word 文档中,并将宽度和高度都设置为 8cm 和 6cm。最后,我们保存了 word 文档。


原文地址: https://www.cveoy.top/t/topic/oA0c 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录