帮我写一个自动截屏的Python代码我用的pycharm软件使用的Python37版本把我电脑CUsersAdministratorDesktopxuexi中的222docx文件中的所有图片宽度修改为14厘米高度为8厘米
以下是一个自动截屏并修改图片大小的Python代码:
import pyautogui
from PIL import Image
# 设置截屏区域和保存路径
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()
代码说明:
- 使用
pyautogui库截取了整个屏幕的截图,并保存到指定路径中。 - 使用
python-docx库打开了指定的Word文档,并遍历了所有内联图片。 - 对每个图片,将其保存到本地并使用
PIL库修改其大小为14厘米宽、8厘米高,并保存到指定路径中。 - 最后关闭Word文档。
注意事项:
- 在使用
python-docx库时,需要先安装lxml和python-docx两个库。 - 由于Word文档中的图片可能有不同的大小和位置,因此修改大小时需要根据实际情况调整
new_width和new_height的值。
原文地址: https://www.cveoy.top/t/topic/bxpY 著作权归作者所有。请勿转载和采集!