Question about PIL's ImageGrab.grab() function...
python - How can I see what did PIL.ImageGrab.grab() captured from a screen? - Stack Overflow
python - Is there any better way to capture the screen than PIL.ImageGrab.grab()? - Stack Overflow
python - Is there a way to use ImageGrab on a specific window? (PIL) - Stack Overflow
Videos
When I capture a certain area of the screen by using ImageGrab.grab(x, x, x, x), which of the values is top right, bottom right, top left, bottom left? Any help is appreciated.
There are many alternatives to PIL.ImageGrab.
If you want cross-platform, nearly every major windowing library has screen grab capabilities. Here's an example using PyQt4:
import sys
from PyQt4.QtGui import QPixmap, QApplication
app = QApplication(sys.argv)
QPixmap.grabWindow(QApplication.desktop().winId()).save('screenshot.jpg', 'jpg')
If you want something different from the default settings for what Qt considers "the desktop", you'll need to dig into the PyQt or Qt documentation.
The downside is that these cross-platform windowing libraries are usually pretty heavy duty in terms of installation, distribution, and even sometimes how you structure your program.
The alternative is to use Windows-specific code. While it's possible to ctypes your way directly to the Windows APIs, a much simpler solution is PyWin32.
import win32gui, win32ui, win32con, win32api
hwin = win32gui.GetDesktopWindow()
width = win32api.GetSystemMetrics(win32con.SM_CXVIRTUALSCREEN)
height = win32api.GetSystemMetrics(win32con.SM_CYVIRTUALSCREEN)
left = win32api.GetSystemMetrics(win32con.SM_XVIRTUALSCREEN)
top = win32api.GetSystemMetrics(win32con.SM_YVIRTUALSCREEN)
hwindc = win32gui.GetWindowDC(hwin)
srcdc = win32ui.CreateDCFromHandle(hwindc)
memdc = srcdc.CreateCompatibleDC()
bmp = win32ui.CreateBitmap()
bmp.CreateCompatibleBitmap(srcdc, width, height)
memdc.SelectObject(bmp)
memdc.BitBlt((0, 0), (width, height), srcdc, (left, top), win32con.SRCCOPY)
bmp.SaveBitmapFile(memdc, 'screenshot.bmp')
As usual with Win32, you have to specify exactly what you mean by "the desktop"; this version specifies the "virtual screen" for the current session, which is the combination of all of the monitors if you're running locally at the console, or the remote view if you're running over Terminal Services. If you want something different, you'll have to read the relevant Win32 documentation at MSDN. But for the most part, translating from that documentation to PyWin32 is trivial.
(By the way, even though I say "Win32", the same all works for Win64.)
A modern cross-platform solution is to use Python MSS.
from mss import mss
from PIL import Image
def capture_screenshot():
# Capture entire screen
with mss() as sct:
monitor = sct.monitors[1]
sct_img = sct.grab(monitor)
# Convert to PIL/Pillow Image
return Image.frombytes('RGB', sct_img.size, sct_img.bgra, 'raw', 'BGRX')
img = capture_screenshot()
img.show()
On my slow laptop this function can return screenshots at up to 27 fps.