以下是一个自动截屏并修改图片大小的Python代码:

import pyautogui
from PIL import Image
from docx import Document

# 设置截屏区域和保存路径
left, top, width, height = 0, 0, 1920, 1080
save_path = 'C:\Users\Administrator\Desktop\xuexi\'

# 截屏并保存
image = pyautogui.screenshot(region=(left, top, width, height))
image.save(save_path + 'screenshot.png')

# 打开Word文档并遍历所有图片
doc_path = save_path + '222.docx'
doc = Document(doc_path)
for idx, image in enumerate(doc.inline_shapes):
    # 修改图片大小并保存
    with open(save_path + f'image{idx}.png', 'wb') as f:
        f.write(image.blob)
    img = Image.open(save_path + f'image{idx}.png')
    width, height = img.size
    new_width, new_height = 14 * 37.8, 8 * 37.8  # 厘米转像素
    img = img.resize((int(new_width), int(new_height)), Image.ANTIALIAS)
    img.save(save_path + f'image{idx}.png')
    
# 关闭Word文档
doc.close()

代码说明:

  1. 使用pyautogui库截取了整个屏幕的截图,并保存到指定路径中。
  2. 使用python-docx库打开了指定的Word文档,并遍历了所有内联图片。
  3. 对每个图片,将其保存到本地并使用PIL库修改其大小为14厘米宽、8厘米高,并保存到指定路径中。
  4. 最后关闭Word文档。

注意事项:

  1. 在使用python-docx库时,需要先安装lxmlpython-docx两个库。
  2. 由于Word文档中的图片可能有不同的大小和位置,因此修改大小时需要根据实际情况调整new_widthnew_height的值。
Python自动截屏并修改Word文档图片大小

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

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