在Mac OS X上使用Python截取屏幕截图

And*_*dré 7 python macos screenshot

来自PIL的ImageGrab本来是理想的.我正在寻找类似的功能,特别是能够定义屏幕截图的边界框.我一直在寻找一个可以在Mac OS X上运行的库,但没有任何运气.我也无法找到任何示例代码(也许是pyobjc?).

Dav*_*ton 16

虽然不完全是你想要的,但在紧要关头你可能会使用:

os.system("screencapture screen.png")
Run Code Online (Sandbox Code Playgroud)

然后使用Image模块打开该图像.我确信存在更好的解决方案.


dbr*_*dbr 10

以下是基于我的答案,如何使用PyObjC捕获和保存屏幕截图

您可以捕获整个屏幕,或指定要捕获的区域.如果您不需要这样做,我建议只调用screencapture命令(更多功能,更强大,更快 - 仅初始PyObjC导入可能需要大约一秒钟)

import Quartz
import LaunchServices
from Cocoa import NSURL
import Quartz.CoreGraphics as CG


def screenshot(path, region = None):
    """region should be a CGRect, something like:

    >>> import Quartz.CoreGraphics as CG
    >>> region = CG.CGRectMake(0, 0, 100, 100)
    >>> sp = ScreenPixel()
    >>> sp.capture(region=region)

    The default region is CG.CGRectInfinite (captures the full screen)
    """

    if region is None:
        region = CG.CGRectInfinite

    # Create screenshot as CGImage
    image = CG.CGWindowListCreateImage(
        region,
        CG.kCGWindowListOptionOnScreenOnly,
        CG.kCGNullWindowID,
        CG.kCGWindowImageDefault)

    dpi = 72 # FIXME: Should query this from somewhere, e.g for retina displays

    url = NSURL.fileURLWithPath_(path)

    dest = Quartz.CGImageDestinationCreateWithURL(
        url,
        LaunchServices.kUTTypePNG, # file type
        1, # 1 image in file
        None
        )

    properties = {
        Quartz.kCGImagePropertyDPIWidth: dpi,
        Quartz.kCGImagePropertyDPIHeight: dpi,
        }

    # Add the image to the destination, characterizing the image with
    # the properties dictionary.
    Quartz.CGImageDestinationAddImage(dest, image, properties)

    # When all the images (only 1 in this example) are added to the destination, 
    # finalize the CGImageDestination object. 
    Quartz.CGImageDestinationFinalize(dest)


if __name__ == '__main__':
    # Capture full screen
    screenshot("/tmp/testscreenshot_full.png")

    # Capture region (100x100 box from top-left)
    region = CG.CGRectMake(0, 0, 100, 100)
    screenshot("/tmp/testscreenshot_partial.png", region=region)
Run Code Online (Sandbox Code Playgroud)


小智 8

虽然我确实知道这个帖子已经接近五年了,但我正在回答这个问题,希望它能在未来帮助人们.

基于这个帖子中的答案,这里有什么对我有用(信用很多):通过python脚本截取屏幕截图.[Linux的]

https://github.com/ponty/pyscreenshot

安装:

easy_install pyscreenshot
Run Code Online (Sandbox Code Playgroud)

例:

import pyscreenshot

# fullscreen
screenshot=pyscreenshot.grab()
screenshot.show()

# part of the screen
screenshot=pyscreenshot.grab(bbox=(10,10,500,500))
screenshot.show()

# save to file
pyscreenshot.grab_to_file('screenshot.png')
Run Code Online (Sandbox Code Playgroud)