我是 Python 新手,试图弄清楚如何使用 pyautogui 截取特定区域的屏幕截图。这是我所拥有的:
import pyautogui
IM = pyautogui.screenshot(region=(20, 20, 500, 500))
IM.save('screen.png')
区域参数不起作用,它每次都会截图我的整个屏幕。 我在 MacOS 上。谢谢您的帮助!
是的,这是 Macos 的一个错误,他们只是忘记添加裁剪逻辑(并且还保存)
我是一个新手(实际上只是第二天才学习Python,因为我可能会错过一些东西,但这可以帮助找到这个答案的人)
我打算针对这个 bug 开启 PR,但我不确定他们会以多快的速度批准(看到 PR 挂了多久)
旧库代码:
def _screenshot_osx(imageFilename=None, region=None):
"""
TODO
"""
# TODO - use tmp name for this file.
if tuple(PIL__version__) < (6, 2, 1):
# Use the screencapture program if Pillow is older than 6.2.1, which
# is when Pillow supported ImageGrab.grab() on macOS. (It may have
# supported it earlier than 6.2.1, but I haven't tested it.)
if imageFilename is None:
tmpFilename = 'screenshot%s.png' % (datetime.datetime.now().strftime('%Y-%m%d_%H-%M-%S-%f'))
else:
tmpFilename = imageFilename
subprocess.call(['screencapture', '-x', tmpFilename])
im = Image.open(tmpFilename)
if region is not None:
assert len(region) == 4, 'region argument must be a tuple of four ints'
region = [int(x) for x in region]
im = im.crop((region[0], region[1], region[2] + region[0], region[3] + region[1]))
os.unlink(tmpFilename) # delete image of entire screen to save cropped version
im.save(tmpFilename)
else:
# force loading before unlinking, Image.open() is lazy
im.load()
if imageFilename is None:
os.unlink(tmpFilename)
else:
# Use ImageGrab.grab() to get the screenshot if Pillow version 6.3.2 or later is installed.
im = ImageGrab.grab()
return im
固定代码:
def _screenshot_osx(imageFilename=None, region=None):
"""
TODO
"""
# TODO - use tmp name for this file.
if tuple(PIL__version__) < (6, 2, 1):
# Use the screencapture program if Pillow is older than 6.2.1, which
# is when Pillow supported ImageGrab.grab() on macOS. (It may have
# supported it earlier than 6.2.1, but I haven't tested it.)
if imageFilename is None:
tmpFilename = 'screenshot%s.png' % (datetime.datetime.now().strftime('%Y-%m%d_%H-%M-%S-%f'))
else:
tmpFilename = imageFilename
subprocess.call(['screencapture', '-x', tmpFilename])
im = Image.open(tmpFilename)
if region is not None:
assert len(region) == 4, 'region argument must be a tuple of four ints'
region = [int(x) for x in region]
im = im.crop((region[0], region[1], region[2] + region[0], region[3] + region[1]))
os.unlink(tmpFilename) # delete image of entire screen to save cropped version
im.save(tmpFilename)
else:
# force loading before unlinking, Image.open() is lazy
im.load()
if imageFilename is None:
os.unlink(tmpFilename)
else:
# Use ImageGrab.grab() to get the screenshot if Pillow version 6.3.2 or later is installed.
im = ImageGrab.grab()
if region is not None:
assert len(region) == 4, 'region argument must be a tuple of four ints'
region = [int(x) for x in region]
im = im.crop((region[0], region[1], region[2] + region[0], region[3] + region[1]))
if imageFilename is not None:
im.save(imageFilename)
return im