怎样实现截图自动保存脚本

wen 实用脚本 27

本文目录导读:

怎样实现截图自动保存脚本

  1. Python + PyAutoGUI(通用方案)
  2. 监听快捷键触发截图
  3. 监控窗口变化的截图
  4. macOS 专用脚本
  5. Windows PowerShell 脚本
  6. 安装依赖
  7. 使用建议

Python + PyAutoGUI(通用方案)

import pyautogui
import time
from datetime import datetime
import os
def auto_screenshot(interval=10, save_dir="screenshots"):
    """自动截图并保存"""
    # 创建保存目录
    if not os.path.exists(save_dir):
        os.makedirs(save_dir)
    try:
        while True:
            # 生成文件名(包含时间戳)
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            filename = f"{save_dir}/screenshot_{timestamp}.png"
            # 截图并保存
            screenshot = pyautogui.screenshot()
            screenshot.save(filename)
            print(f"截图已保存: {filename}")
            # 等待指定时间
            time.sleep(interval)
    except KeyboardInterrupt:
        print("截图程序已停止")
# 每10秒截图一次
auto_screenshot(interval=10)

监听快捷键触发截图

import pyautogui
from datetime import datetime
from pynput import keyboard
import os
class ScreenshotRecorder:
    def __init__(self, save_dir="screenshots"):
        self.save_dir = save_dir
        if not os.path.exists(save_dir):
            os.makedirs(save_dir)
    def take_screenshot(self):
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        filename = f"{self.save_dir}/screenshot_{timestamp}.png"
        screenshot = pyautogui.screenshot()
        screenshot.save(filename)
        print(f"截图已保存: {filename}")
    def start(self):
        print("按 F12 截图,按 ESC 退出")
        def on_press(key):
            try:
                if key == keyboard.Key.f12:
                    self.take_screenshot()
                elif key == keyboard.Key.esc:
                    return False
            except:
                pass
        with keyboard.Listener(on_press=on_press) as listener:
            listener.join()
# 使用示例
recorder = ScreenshotRecorder()
recorder.start()

监控窗口变化的截图

import pyautogui
import time
import hashlib
from PIL import Image
import numpy as np
from datetime import datetime
import os
class SmartScreenshot:
    def __init__(self, region=None, interval=1, save_dir="screenshots"):
        """
        region: (x, y, width, height) 截图区域
        interval: 检测间隔
        """
        self.region = region
        self.interval = interval
        self.save_dir = save_dir
        self.last_hash = None
        if not os.path.exists(save_dir):
            os.makedirs(save_dir)
    def get_image_hash(self, image):
        """计算图片哈希值"""
        # 缩放到32x32并转为灰度
        img = image.resize((32, 32)).convert('L')
        pixels = list(img.getdata())
        avg = sum(pixels) / len(pixels)
        return hashlib.md5(str(pixels > avg).encode()).hexdigest()
    def start_monitoring(self):
        print(f"开始监控区域: {self.region}")
        try:
            while True:
                # 截取指定区域
                if self.region:
                    screenshot = pyautogui.screenshot(region=self.region)
                else:
                    screenshot = pyautogui.screenshot()
                current_hash = self.get_image_hash(screenshot)
                # 检测到变化时保存
                if self.last_hash and current_hash != self.last_hash:
                    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
                    filename = f"{self.save_dir}/change_{timestamp}.png"
                    screenshot.save(filename)
                    print(f"检测到变化,截图已保存: {filename}")
                self.last_hash = current_hash
                time.sleep(self.interval)
        except KeyboardInterrupt:
            print("监控已停止")
# 监控屏幕右上角区域 (x, y, width, height)
monitor = SmartScreenshot(region=(1000, 0, 300, 300))
monitor.start_monitoring()

macOS 专用脚本

#!/bin/bash
# macOS自动截图脚本
# 设置保存目录
SAVE_DIR="$HOME/Screenshots"
mkdir -p "$SAVE_DIR"
while true; do
    # 生成文件名
    TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
    FILENAME="$SAVE_DIR/screenshot_${TIMESTAMP}.png"
    # 使用screencapture命令截图
    screencapture -x "$FILENAME"
    echo "截图已保存: $FILENAME"
    # 等待10秒
    sleep 10
done

Windows PowerShell 脚本

# Windows PowerShell截图脚本
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
$savePath = "$env:USERPROFILE\Screenshots"
if (-not (Test-Path $savePath)) {
    New-Item -ItemType Directory -Path $savePath
}
while ($true) {
    $timestamp = Get-Date -Format "yyyyMMdd_HHmmss"
    $filename = "$savePath\screenshot_$timestamp.png"
    # 创建位图对象
    $bounds = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds
    $bitmap = New-Object System.Drawing.Bitmap $bounds.Width, $bounds.Height
    $graphics = [System.Drawing.Graphics]::FromImage($bitmap)
    $graphics.CopyFromScreen($bounds.X, $bounds.Y, 0, 0, $bounds.Size)
    $bitmap.Save($filename, [System.Drawing.Imaging.ImageFormat]::Png)
    $graphics.Dispose()
    $bitmap.Dispose()
    Write-Host "截图已保存: $filename"
    Start-Sleep -Seconds 10
}

安装依赖

Python脚本需要的包:

pip install pyautogui pillow pynput

macOS脚本: 无需额外安装

Windows脚本: 无需额外安装

使用建议

  1. 定时截图:监控屏幕变化或周期性保存
  2. 快捷键触发:按特定键才截图
  3. 区域监控:只监控特定区域的变化
  4. 智能过滤:检测到实际变化才保存,避免重复

选择适合你需求的方案即可!

抱歉,评论功能暂时关闭!