save_clipboard_image.py
· 805 B · Python
Eredeti
import os
import pyperclip
from datetime import datetime
from PIL import ImageGrab
def save_and_copy_path(save_dir="screenshots"):
# 1. 建立資料夾
if not os.path.exists(save_dir):
os.makedirs(save_dir)
# 2. 抓取剪貼簿影像
img = ImageGrab.grabclipboard()
if img is None:
return "剪貼簿沒影像喔!"
# 3. 產生時間戳記與完整路徑
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
full_path = os.path.abspath(os.path.join(save_dir, f"{timestamp}.png"))
# 4. 儲存影像
img.save(full_path, "PNG")
# 5. 將路徑傳回剪貼簿 (如同 pbcopy)
pyperclip.copy(full_path)
return full_path
if __name__ == "__main__":
result_path = save_and_copy_path()
print(f"路徑已複製:{result_path}")
| 1 | import os |
| 2 | import pyperclip |
| 3 | from datetime import datetime |
| 4 | from PIL import ImageGrab |
| 5 | |
| 6 | def save_and_copy_path(save_dir="screenshots"): |
| 7 | # 1. 建立資料夾 |
| 8 | if not os.path.exists(save_dir): |
| 9 | os.makedirs(save_dir) |
| 10 | |
| 11 | # 2. 抓取剪貼簿影像 |
| 12 | img = ImageGrab.grabclipboard() |
| 13 | |
| 14 | if img is None: |
| 15 | return "剪貼簿沒影像喔!" |
| 16 | |
| 17 | # 3. 產生時間戳記與完整路徑 |
| 18 | timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") |
| 19 | full_path = os.path.abspath(os.path.join(save_dir, f"{timestamp}.png")) |
| 20 | |
| 21 | # 4. 儲存影像 |
| 22 | img.save(full_path, "PNG") |
| 23 | |
| 24 | # 5. 將路徑傳回剪貼簿 (如同 pbcopy) |
| 25 | pyperclip.copy(full_path) |
| 26 | |
| 27 | return full_path |
| 28 | |
| 29 | if __name__ == "__main__": |
| 30 | result_path = save_and_copy_path() |
| 31 | print(f"路徑已複製:{result_path}") |