电脑屏幕截图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_())
再添一个功能类似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已生成。")