-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsave_image.py
More file actions
80 lines (62 loc) · 2.54 KB
/
Copy pathsave_image.py
File metadata and controls
80 lines (62 loc) · 2.54 KB
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
from PIL.Image import Image as ImgType
from pathlib import Path
import json
import os
from image_naming import new_path
from tests_errors import JsonPathErrors, OpenDirPathErrors, CheckInput
DIR_PATH = Path('__file__').resolve().parent
def file_name(f_name: str) -> str:
""" Connects image name with extension and returns the result. """
if '.' in f_name:
if sum(1 for x in f_name if x == '.') > 1:
name = dots_in_string(f_name)
return '.'.join([name, 'jpg'])
name = ''.join(f_name.split('.')[0])
return '.'.join([name, 'jpg'])
return '.'.join([f_name, 'jpg'])
def dots_in_string(st: str) -> str:
""" Returns name of the image if it has multiple dots. """
first_item, second_item = st.split('.', maxsplit=1)
while '.' in second_item:
f_item, second_item = second_item.split(
'.', maxsplit=1)
first_item = '.'.join([first_item, f_item])
return first_item
def folder_path_info(directory_path: Path):
""" Checks if saved path still exists. """
path = json_path(directory_path)
return os.path.exists(path), path
def save_data_path() -> str:
""" Returns full path to the selected folder with the image name or saves
newly selected path and returns it combined with image name. """
input_name = CheckInput(input('Name of the image: '))
f_name: str = file_name(input_name.name)
path_check, folder_path = folder_path_info(DIR_PATH)
if path_check:
path: str = open_dir_path(folder_path)
return '/'.join([path, f_name])
else:
temp_path = CheckInput(input('Path to folder: '))
save_dir_path(temp_path.path, DIR_PATH)
return '/'.join([temp_path.path, f_name])
def save_dir_path(temp_path: str, directory_path: Path) -> None:
""" Saves newly added path to the json file. """
data = {'p': temp_path}
path = json_path(directory_path)
with open(path, 'w') as file:
json.dump(data, file, indent=4)
def json_path(dir_path) -> str:
""" Creates and checks file with the path where images will be saved. """
path = JsonPathErrors(dir_path)
return '/'.join([str(path.folder_path), 'folder_path.json'])
def open_dir_path(json_path: str) -> str:
""" Returns path where images will be saved. """
path = OpenDirPathErrors(json_path)
with open(path.folder_path, 'r') as file:
path = json.load(file)
return path['p']
def image_save(img: ImgType) -> None:
""" Saves image. """
path = save_data_path()
full_path = new_path(path)
img.save(Path(full_path))