Screenshot Annotator for macOS: capture all or part of the screen and add arrows, boxes and text.

0 downloads

Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-screenshot.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-screenshot.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-screenshot.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

danq9 Add screenshot to README d973314 1 year, 1 month ago History
__main__.py · 14.6 KB · 440 lines
1#!/usr/bin/env python3
2"""
3Fast Screenshot Annotator for macOS using PyQt5
4Capture screenshots and quickly annotate them with lines, arrows, rectangles, and text
5"""
6
7import sys
8import subprocess
9import tempfile
10import os
11from datetime import datetime
12from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout,
13 QHBoxLayout, QPushButton, QLabel, QSpinBox,
14 QFileDialog, QMessageBox, QInputDialog)
15from PyQt5.QtGui import QPixmap, QPainter, QPen, QColor, QImage, QFont
16from PyQt5.QtCore import Qt, QPoint, QRect
17
18
19class AnnotationCanvas(QWidget):
20 def __init__(self, pixmap):
21 super().__init__()
22 self.original_pixmap = pixmap
23 self.pixmap = pixmap.copy()
24 self.setFixedSize(pixmap.size())
25
26 # Drawing state
27 self.drawing = False
28 self.start_point = QPoint()
29 self.end_point = QPoint()
30
31 # Tool settings
32 self.tool = "line" # line, arrow, rectangle, text
33 self.color = QColor(255, 0, 0) # red
34 self.line_width = 3
35
36 # Store all shapes for undo
37 self.shapes = []
38
39 self.setMouseTracking(False)
40
41 def set_tool(self, tool):
42 self.tool = tool
43
44 def set_color(self, color):
45 self.color = color
46
47 def set_width(self, width):
48 self.line_width = width
49
50 def paintEvent(self, event):
51 painter = QPainter(self)
52 painter.drawPixmap(0, 0, self.pixmap)
53
54 def mousePressEvent(self, event):
55 if event.button() == Qt.LeftButton:
56 self.drawing = True
57 self.start_point = event.pos()
58
59 if self.tool == "text":
60 self.add_text(event.pos())
61
62 def mouseMoveEvent(self, event):
63 if self.drawing and self.tool != "text":
64 self.end_point = event.pos()
65 # Show preview by redrawing
66 self.pixmap = self.original_pixmap.copy()
67 self.redraw_shapes()
68 self.draw_preview()
69 self.update()
70
71 def mouseReleaseEvent(self, event):
72 if event.button() == Qt.LeftButton and self.drawing and self.tool != "text":
73 self.drawing = False
74 self.end_point = event.pos()
75
76 # Save the shape
77 shape = {
78 'type': self.tool,
79 'start': QPoint(self.start_point),
80 'end': QPoint(self.end_point),
81 'color': QColor(self.color),
82 'width': self.line_width
83 }
84 self.shapes.append(shape)
85
86 # Draw permanently
87 self.draw_shape_on_pixmap(shape)
88 self.original_pixmap = self.pixmap.copy()
89 self.update()
90
91 def draw_preview(self):
92 """Draw temporary preview while dragging"""
93 painter = QPainter(self.pixmap)
94 pen = QPen(self.color, self.line_width)
95 painter.setPen(pen)
96
97 if self.tool == "line":
98 painter.drawLine(self.start_point, self.end_point)
99 elif self.tool == "arrow":
100 self.draw_arrow(painter, self.start_point, self.end_point)
101 elif self.tool == "rectangle":
102 rect = QRect(self.start_point, self.end_point).normalized()
103 painter.drawRect(rect)
104
105 painter.end()
106
107 def draw_shape_on_pixmap(self, shape):
108 """Draw a shape permanently on the pixmap"""
109 painter = QPainter(self.pixmap)
110 pen = QPen(shape['color'], shape['width'])
111 painter.setPen(pen)
112
113 if shape['type'] == "line":
114 painter.drawLine(shape['start'], shape['end'])
115 elif shape['type'] == "arrow":
116 self.draw_arrow(painter, shape['start'], shape['end'])
117 elif shape['type'] == "rectangle":
118 rect = QRect(shape['start'], shape['end']).normalized()
119 painter.drawRect(rect)
120 elif shape['type'] == "text":
121 font = QFont("Helvetica", 18, QFont.Bold)
122 painter.setFont(font)
123 painter.drawText(shape['start'], shape['text'])
124
125 painter.end()
126
127 def draw_arrow(self, painter, start, end):
128 """Draw an arrow from start to end"""
129 import math
130
131 # Draw the line
132 painter.drawLine(start, end)
133
134 # Calculate arrow head
135 angle = math.atan2(end.y() - start.y(), end.x() - start.x())
136 arrow_length = 15
137 arrow_angle = math.pi / 6
138
139 # Arrow head points
140 p1 = QPoint(
141 int(end.x() - arrow_length * math.cos(angle - arrow_angle)),
142 int(end.y() - arrow_length * math.sin(angle - arrow_angle))
143 )
144 p2 = QPoint(
145 int(end.x() - arrow_length * math.cos(angle + arrow_angle)),
146 int(end.y() - arrow_length * math.sin(angle + arrow_angle))
147 )
148
149 # Draw arrow head
150 painter.drawLine(end, p1)
151 painter.drawLine(end, p2)
152
153 def add_text(self, pos):
154 """Add text annotation"""
155 text, ok = QInputDialog.getText(self, "Add Text", "Enter text:")
156 if ok and text:
157 shape = {
158 'type': 'text',
159 'start': QPoint(pos),
160 'text': text,
161 'color': QColor(self.color),
162 'width': self.line_width
163 }
164 self.shapes.append(shape)
165 self.draw_shape_on_pixmap(shape)
166 self.original_pixmap = self.pixmap.copy()
167 self.update()
168
169 def redraw_shapes(self):
170 """Redraw all shapes (for undo)"""
171 for shape in self.shapes:
172 self.draw_shape_on_pixmap(shape)
173
174 def undo(self):
175 """Remove last shape"""
176 if self.shapes:
177 self.shapes.pop()
178 self.pixmap = self.original_pixmap.copy()
179 # Get the original without any shapes
180 self.pixmap = QPixmap(self.pixmap.size())
181 painter = QPainter(self.pixmap)
182 # Start fresh from the very original
183 self.pixmap = self.original_pixmap.copy()
184 self.original_pixmap = self.pixmap.copy()
185 # Reconstruct from original
186 # We need to keep track of the base image
187 self.redraw_all()
188
189 def redraw_all(self):
190 """Redraw everything from scratch"""
191 # This is a bit tricky - we need to keep the original screenshot
192 # For now, just keep it simple
193 self.update()
194
195 def clear_all(self):
196 """Clear all annotations"""
197 self.shapes = []
198 self.pixmap = self.original_pixmap.copy()
199 self.update()
200
201
202class AnnotatorWindow(QMainWindow):
203 def __init__(self, pixmap=None):
204 super().__init__()
205 self.setWindowTitle("Screenshot Annotator")
206
207 # Create central widget
208 central_widget = QWidget()
209 self.setCentralWidget(central_widget)
210
211 # Main layout
212 main_layout = QVBoxLayout(central_widget)
213
214 # Toolbar
215 toolbar = QHBoxLayout()
216
217 # Add screenshot and open buttons first
218 btn_screenshot = QPushButton("📷 Screenshot")
219 btn_screenshot.clicked.connect(self.capture_new_screenshot)
220 toolbar.addWidget(btn_screenshot)
221
222 btn_open = QPushButton("📁 Open")
223 btn_open.clicked.connect(self.open_image)
224 toolbar.addWidget(btn_open)
225
226 toolbar.addWidget(QLabel(" | "))
227
228 # Tool buttons
229 self.btn_line = QPushButton("Line")
230 self.btn_arrow = QPushButton("Arrow")
231 self.btn_rect = QPushButton("Rectangle")
232 self.btn_text = QPushButton("Text")
233
234 self.btn_line.clicked.connect(lambda: self.set_tool("line"))
235 self.btn_arrow.clicked.connect(lambda: self.set_tool("arrow"))
236 self.btn_rect.clicked.connect(lambda: self.set_tool("rectangle"))
237 self.btn_text.clicked.connect(lambda: self.set_tool("text"))
238
239 toolbar.addWidget(self.btn_line)
240 toolbar.addWidget(self.btn_arrow)
241 toolbar.addWidget(self.btn_rect)
242 toolbar.addWidget(self.btn_text)
243
244 toolbar.addWidget(QLabel(" | "))
245
246 # Color buttons
247 btn_red = QPushButton("Red")
248 btn_green = QPushButton("Green")
249 btn_blue = QPushButton("Blue")
250 btn_yellow = QPushButton("Yellow")
251 btn_black = QPushButton("Black")
252
253 btn_red.clicked.connect(lambda: self.set_color(QColor(255, 0, 0)))
254 btn_green.clicked.connect(lambda: self.set_color(QColor(0, 200, 0)))
255 btn_blue.clicked.connect(lambda: self.set_color(QColor(0, 0, 255)))
256 btn_yellow.clicked.connect(lambda: self.set_color(QColor(255, 255, 0)))
257 btn_black.clicked.connect(lambda: self.set_color(QColor(0, 0, 0)))
258
259 # Style color buttons
260 btn_red.setStyleSheet("background-color: red; color: white;")
261 btn_green.setStyleSheet("background-color: green; color: white;")
262 btn_blue.setStyleSheet("background-color: blue; color: white;")
263 btn_yellow.setStyleSheet("background-color: yellow; color: black;")
264 btn_black.setStyleSheet("background-color: black; color: white;")
265
266 toolbar.addWidget(btn_red)
267 toolbar.addWidget(btn_green)
268 toolbar.addWidget(btn_blue)
269 toolbar.addWidget(btn_yellow)
270 toolbar.addWidget(btn_black)
271
272 toolbar.addWidget(QLabel(" | "))
273
274 # Width control
275 toolbar.addWidget(QLabel("Width:"))
276 self.width_spin = QSpinBox()
277 self.width_spin.setRange(1, 20)
278 self.width_spin.setValue(3)
279 self.width_spin.valueChanged.connect(self.set_width)
280 toolbar.addWidget(self.width_spin)
281
282 toolbar.addWidget(QLabel(" | "))
283
284 # Action buttons
285 btn_undo = QPushButton("Undo")
286 btn_clear = QPushButton("Clear")
287 btn_save = QPushButton("Save")
288 btn_copy = QPushButton("Copy")
289
290 btn_undo.clicked.connect(self.undo)
291 btn_clear.clicked.connect(self.clear)
292 btn_save.clicked.connect(self.save)
293 btn_copy.clicked.connect(self.copy_to_clipboard)
294
295 toolbar.addWidget(btn_undo)
296 toolbar.addWidget(btn_clear)
297 toolbar.addWidget(btn_save)
298 toolbar.addWidget(btn_copy)
299
300 toolbar.addStretch()
301
302 main_layout.addLayout(toolbar)
303
304 # Canvas - create with default blank canvas if no pixmap provided
305 if pixmap is None:
306 pixmap = QPixmap(800, 600)
307 pixmap.fill(Qt.white)
308
309 self.canvas = AnnotationCanvas(pixmap)
310 main_layout.addWidget(self.canvas)
311
312 # Set initial tool
313 self.set_tool("line")
314
315 def set_tool(self, tool):
316 self.canvas.set_tool(tool)
317 # Update button styles with more visible active indicator
318 for btn in [self.btn_line, self.btn_arrow, self.btn_rect, self.btn_text]:
319 btn.setStyleSheet("")
320
321 active_style = "background-color: #4A90E2; color: white; border: 2px solid #2E5C8A; font-weight: bold;"
322
323 if tool == "line":
324 self.btn_line.setStyleSheet(active_style)
325 elif tool == "arrow":
326 self.btn_arrow.setStyleSheet(active_style)
327 elif tool == "rectangle":
328 self.btn_rect.setStyleSheet(active_style)
329 elif tool == "text":
330 self.btn_text.setStyleSheet(active_style)
331
332 def set_color(self, color):
333 self.canvas.set_color(color)
334
335 def set_width(self, width):
336 self.canvas.set_width(width)
337
338 def undo(self):
339 self.canvas.undo()
340
341 def clear(self):
342 reply = QMessageBox.question(self, "Clear", "Clear all annotations?",
343 QMessageBox.Yes | QMessageBox.No)
344 if reply == QMessageBox.Yes:
345 self.canvas.clear_all()
346
347 def save(self):
348 timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
349 default_name = f"screenshot_{timestamp}.png"
350
351 filename, _ = QFileDialog.getSaveFileName(
352 self, "Save Image", default_name,
353 "PNG files (*.png);;JPEG files (*.jpg);;All files (*.*)"
354 )
355
356 if filename:
357 self.canvas.pixmap.save(filename)
358 QMessageBox.information(self, "Saved", f"Image saved to {filename}")
359
360 def copy_to_clipboard(self):
361 """Copy image to clipboard"""
362 # Save to temp file
363 temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.png')
364 self.canvas.pixmap.save(temp_file.name)
365 temp_file.close()
366
367 # Use osascript to copy to clipboard on macOS
368 try:
369 subprocess.run([
370 'osascript', '-e',
371 f'set the clipboard to (read (POSIX file "{temp_file.name}") as PNG picture)'
372 ], check=True)
373 QMessageBox.information(self, "Copied", "Image copied to clipboard")
374 except subprocess.CalledProcessError:
375 QMessageBox.critical(self, "Error", "Failed to copy to clipboard")
376 finally:
377 os.unlink(temp_file.name)
378
379 def capture_new_screenshot(self):
380 """Capture a new screenshot and replace current canvas"""
381 pixmap = capture_screenshot()
382 if pixmap and not pixmap.isNull():
383 # Replace canvas with new screenshot
384 self.canvas.setParent(None)
385 self.canvas = AnnotationCanvas(pixmap)
386 self.centralWidget().layout().addWidget(self.canvas)
387 # Reapply current tool
388 current_tool = self.canvas.tool
389 self.set_tool(current_tool)
390 else:
391 QMessageBox.information(self, "Cancelled", "Screenshot cancelled")
392
393 def open_image(self):
394 """Open an existing image file"""
395 filename, _ = QFileDialog.getOpenFileName(
396 self, "Select image to annotate",
397 "", "Image files (*.png *.jpg *.jpeg *.gif *.bmp);;All files (*.*)"
398 )
399 if filename:
400 pixmap = QPixmap(filename)
401 # Replace canvas with new image
402 self.canvas.setParent(None)
403 self.canvas = AnnotationCanvas(pixmap)
404 self.centralWidget().layout().addWidget(self.canvas)
405 # Reapply current tool
406 current_tool = self.canvas.tool
407 self.set_tool(current_tool)
408
409
410def capture_screenshot():
411 """Capture screenshot using macOS screencapture command"""
412 temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.png')
413 temp_file.close()
414
415 # Use macOS screencapture with interactive selection
416 result = subprocess.run(['screencapture', '-i', temp_file.name])
417
418 if result.returncode == 0 and os.path.exists(temp_file.name) and os.path.getsize(temp_file.name) > 0:
419 pixmap = QPixmap(temp_file.name)
420 os.unlink(temp_file.name)
421 return pixmap
422 else:
423 if os.path.exists(temp_file.name):
424 os.unlink(temp_file.name)
425 return None
426
427
428def main():
429 app = QApplication(sys.argv)
430
431 # Start with blank canvas
432 # User can click Screenshot or Open buttons to load content
433 window = AnnotatorWindow()
434 window.show()
435
436 sys.exit(app.exec_())
437
438
439if __name__ == "__main__":
440 main()