302
|
1 #!/usr/bin/python
|
|
2
|
|
3 """
|
|
4 Utility to take a snapshot of the screen
|
|
5 """
|
|
6
|
|
7 import sys
|
|
8 from PyQt5.QtGui import QGuiApplication, QPainter, QPen
|
|
9 from PyQt5.QtCore import QRect, Qt, pyqtSignal, QBuffer
|
|
10 from PyQt5.QtWidgets import QApplication, QWidget
|
|
11
|
|
12
|
|
13 class RegionSelecter(QWidget):
|
|
14 sigBitmap = pyqtSignal(bytes)
|
|
15 def __init__(self):
|
|
16 super().__init__()
|
|
17 screen = QGuiApplication.primaryScreen()
|
|
18 self.desktopPixmap = screen.grabWindow(0)
|
|
19 self.setWindowFlags(Qt.FramelessWindowHint | Qt.X11BypassWindowManagerHint | Qt.WindowStaysOnTopHint)
|
|
20 self.setWindowState(Qt.WindowFullScreen)
|
|
21 self.move(0, 0)
|
|
22 self.resize(self.desktopPixmap.size())
|
|
23 self.drawSelection = False
|
|
24
|
|
25 @property
|
|
26 def Selection(self):
|
|
27 return QRect(self.startPoint, self.endPoint).normalized()
|
|
28
|
|
29 def paintEvent(self, ev):
|
|
30 painter = QPainter(self)
|
|
31 painter.drawPixmap(0, 0, self.desktopPixmap)
|
|
32 if self.drawSelection:
|
|
33 painter.setPen(QPen(Qt.red))
|
|
34 painter.drawRect(self.Selection)
|
|
35
|
|
36 def mousePressEvent(self, ev):
|
|
37 self.startPoint = ev.pos()
|
|
38 self.endPoint = ev.pos()
|
|
39 self.drawSelection = True
|
|
40
|
|
41 def mouseMoveEvent(self, ev):
|
|
42 self.update()
|
|
43 self.endPoint = ev.pos()
|
|
44
|
|
45 def mouseReleaseEvent(self, ev):
|
|
46 self.endPoint = ev.pos()
|
|
47 pm = self.desktopPixmap.copy(self.Selection)
|
|
48 memfile = QBuffer()
|
|
49 pm.save(memfile, "png")
|
|
50 self.sigBitmap.emit(bytes(memfile.data()))
|
|
51
|
|
52
|
|
53 def takeShot():
|
|
54 app = QApplication(sys.argv)
|
|
55 screen = QGuiApplication.primaryScreen()
|
|
56 desktopPixmap = screen.grabWindow(0)
|
|
57 desktopPixmap.save('tst2.png')
|
|
58
|
|
59
|
|
60 def takeRegion():
|
|
61 """ Take a snapshot of the current desktop """
|
|
62 app = QApplication(sys.argv)
|
|
63 r = RegionSelecter()
|
|
64 TMP = {}
|
|
65 def handleBitmap(bm):
|
|
66 app.quit()
|
|
67 TMP['bm'] = bm
|
|
68 r.sigBitmap.connect(handleBitmap)
|
|
69 r.show()
|
|
70 app.exec()
|
|
71 return TMP['bm']
|
|
72
|
|
73
|
|
74 if __name__ == '__main__':
|
|
75 bm = takeRegion()
|
|
76 print(bm)
|
|
77 with open('tst.png', 'wb') as f:
|
|
78 f.write(bm)
|