Comments¶
- PIL.ImageGrab works on macOS and Windows only.
PIL.ImageGrab
is relatively slow.python-mss
andPyQt5
are better alternatives if performance of screenshot is critical. Notice that saving an (e.g., PNG) image can take significant time (might take up to 0.5 seconds) too, this is often due to image compression is slow. Lower the compression level can significant reduce the time needed to save an image. Please refer to Saving a PNG file is slow for more discussions.You can further crop a screenshot image using the method
PIL.Image.crop
.If you are using macOS, you need to grant
Screen Recording
access to your application viaSystem Preferences...
. For example, if you run Python in Hyper, you need to grant Hyper permission to accessScreen Recording
.
Pillow¶
import numpy as np
from PIL import Image, ImageGrab
ImageGrab.grab(bbox=(10, 10, 510, 510))
pyscreenshot¶
pyscreenshot is a simple wrapper over various back-ends. Please refer to the Features section for supported back-ends. One of the back-ends must be installed for pyscreenshot to work.
import pyscreenshot as pyss
pyss.grab()
PIL.ImageGrab.grab(bbox=(10, 10, 510, 510))
python-mss¶
python-mss
is an ultra fast cross-platform multiple screenshots module in pure Python using ctypes.
It is about 10 times faster than Pillow.Image.grab
.
from mss import mss
# The simplest use, save a screen shot of the 1st monitor
with mss() as sct:
sct.shot()
import mss
import mss.tools
with mss.mss() as sct:
# the screen part to capture
monitor = {"top": 160, "left": 160, "width": 160, "height": 135}
# grab the data
sct_img = sct.grab(monitor)
# save the screenshot as a PNG image
output = "sct-{top}x{left}_{width}x{height}.png".format(**monitor)
mss.tools.to_png(sct_img.rgb, sct_img.size, output=output)
print(output)
Convert the data to a Pillow Image.
from PIL import Image
img = Image.frombytes("RGB", sct_img.size, sct_img.bgra, "raw", "BGRX")
mss.mss.grab¶
Takes a dict (containing keys "left", "top", "width" and "height") and parameter.
Unlike Pillow.Image.grab
,
mss.mss.grab
uses the same coordinates shown on the screen.
However,
the resulting image's dimension (width 2, height 2).
PyQt5¶
from PyQt5.QtGui import QPixmap, QApplication
from datetime import datetime
app = QApplication([])
while True:
date = datetime.now()
filename = r"C:/%s.jpg" % date.strftime("%m/%d/%Y_%H.%M.%S-%f")
QPixmap.grabWindow(QApplication.desktop().winId()).save(filename, "jpg")