在 Python 中,您可以使用多种方法将屏幕截图保存为 PNG 格式。以下是几种常用的方法:

  1. 使用 PIL 库 (Python Imaging Library):

PIL 是 Python 中一个强大的图像处理库,可以用来打开、处理和保存图像。您可以使用 PIL 库的 ImageGrab 模块来实现截图,并使用 save 方法将图像保存为 PNG 格式。

from PIL import ImageGrab

screenshot = ImageGrab.grab()  # 截图
screenshot.save('screenshot.png', 'PNG')  # 保存为 PNG 格式
  1. 使用 pyautogui 库:

pyautogui 是一个用于自动化鼠标和键盘操作的库,它也提供了截图功能。您可以使用 screenshot 函数来实现截图,并使用 save 方法将图像保存为 PNG 格式。

import pyautogui

screenshot = pyautogui.screenshot()  # 截图
screenshot.save('screenshot.png')  # 保存为 PNG 格式
  1. 使用 OpenCV 库:

OpenCV 是一个用于计算机视觉和图像处理的开源库,也可以用来进行截图和保存为 PNG 格式。

import cv2
import numpy as np
import pyautogui

# 获取屏幕尺寸
screen_size = (1920, 1080)  # 假设屏幕尺寸为 1920x1080

# 从屏幕获取图像
screenshot = pyautogui.screenshot()
screenshot = cv2.cvtColor(np.array(screenshot), cv2.COLOR_RGB2BGR)

# 保存为 PNG 格式
cv2.imwrite('screenshot.png', screenshot)

这些方法中,PIL 库和 pyautogui 库是比较常用的截图库,而 OpenCV 库则提供了更多的图像处理功能。根据具体的需求,可以选择适合自己的方法。

Python 截图保存为 PNG 格式的最佳方法

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

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