吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 1302|回复: 10
收起左侧

[Python 原创] python 实现屏幕gif截图

  [复制链接]
aa4569021 发表于 2024-6-28 16:57
无聊搞了个, 电脑屏幕截图gif 图片的功能, 新手实现,大佬勿喷,
win32clipboard 库默认python3.8 版本, 其他版本可能又报错默认注释,
添加该库默认为了保存文件后自动复制到剪贴板

[Python] 纯文本查看 复制代码
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_())

开始选择区域

开始选择区域

截取时常秒

截取时常秒

免费评分

参与人数 2吾爱币 +8 热心值 +2 收起 理由
苏紫方璇 + 7 + 1 欢迎分析讨论交流,吾爱破解论坛有你更精彩!
laozhang4201 + 1 + 1 热心回复!

查看全部评分

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

congge5201 发表于 2024-6-28 18:01
[Python] 纯文本查看 复制代码
import cv2
import numpy as np
import pygetwindow as gw
import time
import imageio

# 获取当前活动窗口的句柄
active_window = gw.getActiveWindow()
window_title = active_window.title

# 获取窗口的尺寸
window_size = active_window.size

# 设置视频编码器
fourcc = cv2.VideoWriter_fourcc(*'XVID')

# 创建VideoWriter对象
out = cv2.VideoWriter('output.avi', fourcc, 20.0, (window_size.width, window_size.height))

# 开始录像
print("开始录像...")
start_time = time.time()
while True:
    # 获取当前窗口的截图
    screenshot = active_window.screenshot()
    # 将截图转换为BGR格式
    frame = cv2.cvtColor(np.array(screenshot), cv2.COLOR_RGB2BGR)
    # 写入帧
    out.write(frame)
    # 显示帧
    cv2.imshow('frame', frame)
    # 按'q'退出
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# 释放VideoWriter对象
out.release()
# 关闭所有OpenCV窗口
cv2.destroyAllWindows()
# 计算录像时间
end_time = time.time()
print(f"录像结束,录像时长:{end_time - start_time}秒")

# 将视频转换为GIF
frames = []
video = cv2.VideoCapture('output.avi')
while True:
    ret, frame = video.read()
    if not ret:
        break
    frames.append(frame)
video.release()

# 保存为GIF
imageio.mimsave('output.gif', frames, 'GIF', duration=0.1)

print("GIF已生成。")

免费评分

参与人数 1吾爱币 +1 热心值 +1 收起 理由
helian147 + 1 + 1 热心回复!

查看全部评分

yysygy 发表于 2024-6-28 18:11
CRG_44 发表于 2024-6-29 07:31
tianmenghuan 发表于 2024-6-29 09:11
这个可以试试  感谢分享
Yifan2007 发表于 2024-6-29 09:17


其实还是截图,然后合成
龍謹 发表于 2024-6-29 09:42
这贴是我这种小白学习的PY好资料
行走的bug 发表于 2024-6-29 09:51
666,谢谢分享!
RabbitBearLove 发表于 2024-6-29 15:59
很有意思,学习一下
谢谢楼主分享
hellopojie520 发表于 2024-8-22 18:49
怎么是两个代码?要分别运行吗
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-12-15 16:35

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表