[Python] Taking and Saving Screenshots with PyAutoGUI

目次

Overview

This article explains how to capture your current screen using the screenshot() function in PyAutoGUI. We will cover various methods, from simply saving a file to obtaining a Pillow (PIL) Image object for use within a program, as well as capturing specific areas of the screen.

Specifications

  • Input:
    • Save file path (optional).
    • Capture area region=(left, top, width, height) (optional).
  • Output:
    • Image file generation (such as PNG).
    • Image object in Python (for handling in memory without saving to a file).
  • Requirements:
    • The pyautogui library must be installed.
    • Linux environments may require the scrot command.

Basic Usage

This is the most basic code to capture and save the entire screen by specifying a filename.

import pyautogui

# Capture the entire screen and save it as "screenshot.png"
pyautogui.screenshot("screenshot.png")

Full Code Example

The following sample code implements three patterns: saving directly to a file, capturing into memory, and specifying a range.

import pyautogui
import os

def capture_screen_demo():
    """
    Executes various patterns for taking screenshots.
    """
    try:
        # 1. Save directly by specifying a filename
        filename_full = "capture_fullscreen.png"
        print(f"Saving full screen capture: {filename_full}")
        pyautogui.screenshot(filename_full)

        # 2. Get as an Image object and then save
        # (Useful when you want to process the image before saving)
        print("Retrieving image in memory...")
        img = pyautogui.screenshot()
        
        # The retrieved object is a Pillow Image class
        print(f"Image size: {img.size}")
        
        filename_obj = "capture_from_object.png"
        img.save(filename_obj)
        print(f"Saved from object: {filename_obj}")

        # 3. Capture a specific range (region argument)
        # region=(Left X, Top Y, Width, Height)
        region_rect = (0, 0, 300, 300)
        filename_region = "capture_region.png"
        
        print(f"Capturing top-left 300x300: {filename_region}")
        pyautogui.screenshot(filename_region, region=region_rect)

        print("All processes completed.")

    except Exception as e:
        print(f"An error occurred: {e}")

if __name__ == "__main__":
    capture_screen_demo()

Customization Points

The screenshot() function is simple, but you can control its behavior with the following arguments.

imageFilename (1st argument)

If you specify a path as a string, the file is saved automatically. If omitted, the file is not saved, and the function returns an Image object.

region

By specifying a tuple of (x, y, width, height), you can crop and capture only a part of the screen. Limiting the processing range helps reduce load and exclude unnecessary information.

Important Notes

Overwriting Existing Files

If a file with the specified name already exists, it will be overwritten immediately without confirmation. It is recommended to add timestamps to filenames to prevent deleting important files.

OS Dependencies

  • Linux: You may need to install screenshot tools using a command like sudo apt-get install scrot, or an error may occur.
  • Mac/Windows: Generally works without additional settings.

Execution Speed

The screenshot() function is not extremely fast because it involves disk I/O and image conversion. It is not suitable for real-time processing that requires millisecond accuracy, such as frame-by-frame processing in games.

Advanced Application

This example creates a logger that includes the current date and time in the filename to allow continuous saving without duplicates.

import pyautogui
import time
from datetime import datetime
import os

def timestamp_screenshot():
    """
    Saves a screenshot with the current time included in the filename.
    """
    # Create directory for saving
    save_dir = "screenshots"
    os.makedirs(save_dir, exist_ok=True)

    # Generate filename in YYYYMMDD_HHMMSS format
    now = datetime.now().strftime("%Y%m%d_%H%M%S")
    filename = f"screen_{now}.png"
    filepath = os.path.join(save_dir, filename)

    print(f"Saving: {filepath}")
    pyautogui.screenshot(filepath)

if __name__ == "__main__":
    timestamp_screenshot()

Summary

pyautogui.screenshot() is very useful for saving evidence in automation scripts or recording conditions when errors occur. By using the region argument to save only necessary information and managing files with timestamps, you can easily build a practical log collection system.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次