python 实现屏幕gif截图

win32clipboard 库默认python3.8 版本, 其他版本可能又报错默认注释,
添加该库默认为了保存文件后自动复制到剪贴板

import sys
import time
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QLabel, QFileDialog, QInputDialog
from PyQt5.QtCore import Qt, QRect
from PyQt5.QtGui import QPainter, QPen, QColor
from PIL import Image
import mss
# import win32clipboard
from io import BytesIO
 
 
class ScreenshotTool(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
 
    def initUI(self):
        self.setWindowTitle('Screenshot Tool')
        self.setGeometry(300, 300, 300, 200)
 
        layout = QVBoxLayout()
 
        self.label = QLabel('Click and drag to select area')
        layout.addWidget(self.label)
 
        self.button = QPushButton('Start Screenshot', self)
        self.button.clicked.connect(self.start_screenshot)
        layout.addWidget(self.button)
 
        self.setLayout(layout)
 
    def start_screenshot(self):
        duration, ok = QInputDialog.getInt(self, "Capture Duration", "Enter capture duration in seconds:", 5, 1, 60)
        if ok:
            self.hide()  # Hide the main window
            self.screenshot_widget = ScreenshotWidget(duration)
            self.screenshot_widget.show()
 
 
class ScreenshotWidget(QWidget):
    def __init__(self, duration):
        super().__init__()
        self.duration = duration
        self.setGeometry(0, 0, QApplication.desktop().screenGeometry().width(),
                         QApplication.desktop().screenGeometry().height())
        self.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint | Qt.Tool)
        self.setWindowOpacity(0.3)
        self.begin = None
        self.end = None
 
    def paintEvent(self, event):
        if self.begin and self.end:
            qp = QPainter(self)
            qp.setPen(QPen(QColor(255, 0, 0), 2, Qt.SolidLine))
            qp.drawRect(QRect(self.begin, self.end))
 
    def mousePressEvent(self, event):
        self.begin = event.pos()
        self.end = event.pos()
        self.update()
 
    def mouseMoveEvent(self, event):
        self.end = event.pos()
        self.update()
 
    def mouseReleaseEvent(self, event):
        self.hide()
        x1 = min(self.begin.x(), self.end.x())
        y1 = min(self.begin.y(), self.end.y())
        x2 = max(self.begin.x(), self.end.x())
        y2 = max(self.begin.y(), self.end.y())
 
        self.capture_screen(x1, y1, x2 - x1, y2 - y1)
 
    def capture_screen(self, x, y, width, height):
        frames = []
        fps = 10  # frames per second
        frame_count = self.duration * fps
 
        with mss.mss() as sct:
            monitor = {"top": y, "left": x, "width": width, "height": height}
 
            for _ in range(frame_count):
                screenshot = sct.grab(monitor)
                img = Image.frombytes("RGB", screenshot.size, screenshot.bgra, "raw", "BGRX")
                frames.append(img)
                time.sleep(1 / fps)
 
        file_path, _ = QFileDialog.getSaveFileName(self, "Save File", "", "GIF (*.gif)")
 
        if file_path:
            frames[0].save(file_path, save_all=True, append_images=frames[1:],
                           duration=1000 / fps, loop=0)
            print(f"GIF saved to {file_path}")
            self.copy_to_clipboard(file_path)
 
        QApplication.quit()
 
    def copy_to_clipboard(self, file_path):
        image = Image.open(file_path)
        output = BytesIO()
        image.convert("RGB").save(output, "BMP")
        data = output.getvalue()[14:]
        output.close()
 
        # 文件复制到剪贴板
        # win32clipboard.OpenClipboard()
        # win32clipboard.EmptyClipboard()
        # win32clipboard.SetClipboardData(win32clipboard.CF_DIB, data)
        # win32clipboard.CloseClipboard()
 
        print("GIF copied to clipboard")
 
 
if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = ScreenshotTool()
    ex.show()
    sys.exit(app.exec_())

  • 16
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

数据服务生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值