-
Notifications
You must be signed in to change notification settings - Fork 0
/
screenshot.py
58 lines (48 loc) · 2.05 KB
/
screenshot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
from pynput import mouse, keyboard
from PIL import ImageGrab
import threading
# Global variables to store the coordinates
start_x = start_y = end_x = end_y = None
hotkey = '<ctrl>+<alt>+k' # Define the hotkey (Ctrl+Alt+S)
def on_click(x, y, button, pressed):
global start_x, start_y, end_x, end_y
if pressed:
# Record the start position when mouse is pressed
start_x, start_y = x, y
else:
# Record the end position when mouse is released
end_x, end_y = x, y
# Stop listener
return False
def crop_screenshot(img, start_x, start_y, end_x, end_y):
# Normalize coordinates (make sure start is top-left, end is bottom-right)
left = min(start_x, end_x)
top = min(start_y, end_y)
right = max(start_x, end_x)
bottom = max(start_y, end_y)
# Crop the image using the specified coordinates
cropped_img = img.crop((left, top, right, bottom))
#cropped_img.save("cropped_screenshot.png") # Save the cropped screenshot
return cropped_img
def take_and_crop_screenshot(image_file_path):
# Take a full-screen screenshot
full_screenshot = ImageGrab.grab()
# Collect mouse events until released
with mouse.Listener(on_click=on_click) as listener:
listener.join()
# Once mouse listener is done, crop the screenshot
if start_x is not None and start_y is not None and end_x is not None and end_y is not None:
cropped_img = crop_screenshot(full_screenshot, start_x, start_y, end_x, end_y)
cropped_img.save(image_file_path)
else:
print("No area selected.")
def take_and_crop_screenshot_thread(image_file_path):
print("Hotkey activated! Taking screenshot...")
screenshot_thread = threading.Thread(target=take_and_crop_screenshot,args=(image_file_path,))
screenshot_thread.start()
def for_canonical(f):
return lambda k: f(listener.canonical(k))
if __name__ == "__main__":
# Define a hotkey listener
with keyboard.GlobalHotKeys({hotkey:lambda: take_and_crop_screenshot_thread('./screenshot.png')}) as listener:
listener.join()