macos 在 Mac OS X 上用 Python 截取屏幕截图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4524723/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Take screenshot in Python on Mac OS X
提问by André
ImageGrab from PIL would have been ideal. I'm looking for similar functionality, specifically the ability to define the screenshot's bounding box. I've been looking for a library to do so on Mac OS X but haven't had any luck. I also wasn't able to find any sample code to do it (maybe pyobjc?).
来自 PIL 的 ImageGrab 本来是理想的。我正在寻找类似的功能,特别是能够定义屏幕截图的边界框。我一直在寻找一个库来在 Mac OS X 上这样做,但没有任何运气。我也找不到任何示例代码来做到这一点(也许是 pyobjc?)。
回答by David Morton
While not exactly what you want, in a pinch you might just use:
虽然不完全是你想要的,但在紧要关头你可能会使用:
os.system("screencapture screen.png")
Then open that image with the Image module. I'm sure a better solution exists though.
然后使用图像模块打开该图像。不过,我确信存在更好的解决方案。
回答by dbr
Here's how to capture and save a screenshot with PyObjC, based on my answer here
以下是根据我在此处的回答,使用 PyObjC 捕获和保存屏幕截图的方法
You can capture the entire screen, or specify a region to capture. If you don't need to do that, I'd recommend just calling the screencapture
command (more features, more robust, and quicker - the initial PyObjC import alone can take around a second)
您可以捕获整个屏幕,或指定要捕获的区域。如果您不需要这样做,我建议您只调用该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)
回答by Mithru
While I do understand that this thread is close to five years old now, I'm answering this in the hope that it helps people in future.
虽然我确实知道这个线程现在已经快五年了,但我正在回答这个问题,希望它在未来对人们有所帮助。
Here's what worked for me, based on an answer in this thread (credit goes to ponty) : Take a screenshot via a python script. [Linux]
根据此线程中的答案(归功于ponty),这是对我有用的方法:通过 python 脚本截取屏幕截图。[Linux]
https://github.com/ponty/pyscreenshot
https://github.com/ponty/pyscreenshot
Install:
安装:
easy_install pyscreenshot
Example:
例子:
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')
回答by isep
Pillow has since added ImageGrabsupport for macOS!
Pillow 已经为 macOS添加了ImageGrab支持!
However it's not in v2.9 (as of right now the latest) so I just added this file to my local module.
但是它不在 v2.9(截至目前最新)中,所以我只是将此文件添加到我的本地模块中。
The code is as below:
代码如下:
#
# The Python Imaging Library
# $Id$
#
# screen grabber (macOS and Windows only)
#
# History:
# 2001-04-26 fl created
# 2001-09-17 fl use builtin driver, if present
# 2002-11-19 fl added grabclipboard support
#
# Copyright (c) 2001-2002 by Secret Labs AB
# Copyright (c) 2001-2002 by Fredrik Lundh
#
# See the README file for information on usage and redistribution.
#
from . import Image
import sys
if sys.platform not in ["win32", "darwin"]:
raise ImportError("ImageGrab is macOS and Windows only")
if sys.platform == "win32":
grabber = Image.core.grabscreen
elif sys.platform == "darwin":
import os
import tempfile
import subprocess
def grab(bbox=None):
if sys.platform == "darwin":
fh, filepath = tempfile.mkstemp('.png')
os.close(fh)
subprocess.call(['screencapture', '-x', filepath])
im = Image.open(filepath)
im.load()
os.unlink(filepath)
else:
size, data = grabber()
im = Image.frombytes(
"RGB", size, data,
# RGB, 32-bit line padding, origin lower left corner
"raw", "BGR", (size[0]*3 + 3) & -4, -1
)
if bbox:
im = im.crop(bbox)
return im
def grabclipboard():
if sys.platform == "darwin":
fh, filepath = tempfile.mkstemp('.jpg')
os.close(fh)
commands = [
"set theFile to (open for access POSIX file \""+filepath+"\" with write permission)",
"try",
"write (the clipboard as JPEG picture) to theFile",
"end try",
"close access theFile"
]
script = ["osascript"]
for command in commands:
script += ["-e", command]
subprocess.call(script)
im = None
if os.stat(filepath).st_size != 0:
im = Image.open(filepath)
im.load()
os.unlink(filepath)
return im
else:
debug = 0 # temporary interface
data = Image.core.grabclipboard(debug)
if isinstance(data, bytes):
from . import BmpImagePlugin
import io
return BmpImagePlugin.DibImageFile(io.BytesIO(data))
return data
回答by Ankush Choudhary
from subprocess import call
import time
from time import gmtime, strftime
# Take screenshot every 10 seconds and store in the folder where the
# code file is present on disk. To stop the script press Cmd+Z/C
def take_screen_shot():
# save screen shots where
call(["screencapture", "Screenshot" + strftime("%Y-%m-%d %H:%M:%S", gmtime()) + ".jpg"])
def build_screen_shot_base():
while True:
take_screen_shot()
time.sleep(10)
build_screen_shot_base()
回答by zekel
I found that using webkit2pngwas the most convenient solution for me on OS X.
我发现在 OS X 上使用webkit2png对我来说是最方便的解决方案。
brew install webkit2png
webkit2png http://stackoverflow.com