-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsave_pic_from_clipboard.py
195 lines (154 loc) · 6.28 KB
/
save_pic_from_clipboard.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
from PIL import Image, ImageGrab
import sys
import os
import json
import argparse
import settings
from utils import md5_hash
from colorprt import ColorprtConfig, Fore, colorstr
green = ColorprtConfig(Fore.GREEN)
blue = ColorprtConfig(Fore.BLUE)
red = ColorprtConfig(Fore.RED)
def parser_init():
parser = argparse.ArgumentParser()
parser.add_argument('--clear-cache', required=False, action='store_true', dest='clear')
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("-i", "--init", help="init the saving settings", required=False, action="store_true")
group.add_argument("-n", "--name", help="the saved pic name", required=False)
parser.add_argument("-f", "--folder", help="the saved pic folder", required=False)
parser.add_argument("--info", required=False, action="store_true", help="print settings")
parser.add_argument("-t", "--type", required=False, help="set pic type", default='.png', choices=['.jpg', '.png'])
return parser
class Config:
class InitError(Exception):
def __init__(self, *args) -> None:
super().__init__(*args)
CONFIG_INIT = {
"save folder": os.path.abspath('.'),
"pic type": ".png",
"hash": md5_hash(os.path.abspath('.'))
}
def __init__(self) -> None:
self.config_file_path = settings.CONFIG_FILE
self.config_file = []
self.config = self.CONFIG_INIT
self.cur_config_idx = -1
self.load_config()
def load_config(self):
if not os.path.exists(self.config_file_path):
try:
os.mkdir(f'{settings.userpath}/.save_pic')
except OSError as e:
if settings.DEBUG:
print(e)
with open(self.config_file_path, 'w') as f:
json.dump(self.config_file, f, indent=4, ensure_ascii=False)
with open(self.config_file_path, 'r') as f:
self.config_file = json.load(f)
def get_cur_config(self, folder_name):
hash_res = md5_hash(folder_name)
for idx, config in enumerate(self.config_file):
if config['hash'] == hash_res:
self.cur_config_idx = idx
self.config = config
return True
return False
def change_type(self, tp: str):
self.config['pic type'] = tp
def change_save_path(self, path: str):
if os.path.isabs(path):
self.config['save folder'] = os.path.join(os.path.abspath('.'), path)
else:
self.config['save folder'] = path
# def delete_config(self, idx):
# for config in self.config_file:
# if idx == config['idx']:
# self.config_file.remove(config)
# break
def save_cur_config(self):
if len(self.config_file) > 0:
if self.cur_config_idx == -1:
# self.config['id'] = self.config_file[-1]['id'] + 1
self.config_file.append(self.config)
self.cur_config_idx = len(self.config_file) - 1
else:
self.config_file[self.cur_config_idx] = self.config
else:
self.config_file.append(self.config)
self.cur_config_idx = 0
def init(self):
if self.cur_config_idx != -1:
blue.print("You have init this folder. Are you sure to init again? (Y/N)", end='')
choice = str(input())
if choice in ['Y', 'y']:
self.config = self.CONFIG_INIT
elif choice in ['N', 'n']:
pass
else:
print("Wrong Choices")
sys.exit(-1)
def clear_cache(self):
self.config_file.clear()
self.save_cur_config()
def save_config(self):
with open(self.config_file_path, 'w') as f:
json.dump(self.config_file, f, indent=4, ensure_ascii=False)
class SaveClipBoardPic():
def __init__(self, args) -> None:
self.config = Config()
self.cur_path = os.getcwd()
if settings.DEBUG:
print(os.getcwd())
print(os.path.abspath('.'))
print(md5_hash(self.cur_path))
self.config.get_cur_config(self.cur_path)
self.params = args
self.check_params()
def check_params(self):
if (self.params.init):
self.init_setting()
if (self.params.folder):
self.change_folder(os.path.abspath(self.params.folder.strip()))
if (self.params.type):
self.change_type(self.params.type.strip())
if (self.params.name):
self.save(self.params.name.strip())
if (self.params.info):
self.show_settings()
if (self.params.clear):
self.config.clear_cache()
self.config.save_config()
def show_settings(self):
print(colorstr("saved folder path: ", config=blue), self.config.config['save folder'])
print(colorstr("picture type: ", config=blue), self.config.config['pic type'])
def save(self, file_name: str):
im = ImageGrab.grabclipboard()
file_dict = self.config.config
if isinstance(im, Image.Image):
green.print("image:size:%s, mode: %s" % (im.size, im.mode))
try:
im.save(os.path.join(file_dict["save folder"], file_name + file_dict["pic type"]))
green.print("pic is saved in path:\"{}\"".format(
os.path.join(file_dict["save folder"], file_name + file_dict["pic type"])))
except FileNotFoundError as e:
red.print(e.strerror)
red.print("use -i to init folder or use --folder to set another folder")
sys.exit(-1)
else:
print("no pic in clipboard.")
self.config.save_cur_config()
self.config.save_config()
def init_setting(self):
self.config.init()
self.config.save_cur_config()
self.config.save_config()
def change_folder(self, folder_name: str):
self.config.change_save_path(folder_name)
self.config.save_cur_config()
self.config.save_config()
def change_type(self, tp: str):
self.config.change_type(tp)
self.config.save_cur_config()
self.config.save_config()
if __name__ == "__main__":
SaveClipBoardPic(args=parser_init().parse_args())