batch-img 0.0.7__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- batch_img/__init__.py +0 -0
- batch_img/border.py +86 -0
- batch_img/common.py +259 -0
- batch_img/const.py +26 -0
- batch_img/defaults.py +134 -0
- batch_img/interface.py +148 -0
- batch_img/main.py +137 -0
- batch_img/orientation.py +112 -0
- batch_img/resize.py +79 -0
- batch_img/rotate.py +121 -0
- batch_img-0.0.7.dist-info/METADATA +154 -0
- batch_img-0.0.7.dist-info/RECORD +16 -0
- batch_img-0.0.7.dist-info/WHEEL +5 -0
- batch_img-0.0.7.dist-info/entry_points.txt +2 -0
- batch_img-0.0.7.dist-info/licenses/LICENSE +21 -0
- batch_img-0.0.7.dist-info/top_level.txt +1 -0
batch_img/__init__.py
ADDED
|
File without changes
|
batch_img/border.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""class Border: add border to the image file(s)
|
|
2
|
+
Copyright © 2025 John Liu
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
import piexif
|
|
8
|
+
import pillow_heif
|
|
9
|
+
from loguru import logger
|
|
10
|
+
from PIL import Image
|
|
11
|
+
|
|
12
|
+
from batch_img.common import Common
|
|
13
|
+
|
|
14
|
+
pillow_heif.register_heif_opener() # allow Pillow to open HEIC files
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class Border:
|
|
18
|
+
@staticmethod
|
|
19
|
+
def add_border_1_image(
|
|
20
|
+
in_path: Path, out_path: Path, border_width: int, border_color: str
|
|
21
|
+
) -> tuple:
|
|
22
|
+
"""Add internal border to an image file, not to expand the size
|
|
23
|
+
|
|
24
|
+
Args:
|
|
25
|
+
in_path: input file path
|
|
26
|
+
out_path: output dir path
|
|
27
|
+
border_width: border width int
|
|
28
|
+
border_color: border color str
|
|
29
|
+
|
|
30
|
+
Returns:
|
|
31
|
+
tuple: bool, str
|
|
32
|
+
"""
|
|
33
|
+
try:
|
|
34
|
+
with Image.open(in_path) as img:
|
|
35
|
+
width, height = img.size
|
|
36
|
+
box = Common.get_crop_box(width, height, border_width)
|
|
37
|
+
cropped_img = img.crop(box)
|
|
38
|
+
bd_img = Image.new(img.mode, (width, height), border_color)
|
|
39
|
+
bd_img.paste(cropped_img, (border_width, border_width))
|
|
40
|
+
|
|
41
|
+
out_path.mkdir(parents=True, exist_ok=True)
|
|
42
|
+
out_file = out_path
|
|
43
|
+
if out_path.is_dir():
|
|
44
|
+
filename = f"{in_path.stem}_bw{border_width}{in_path.suffix}"
|
|
45
|
+
out_file = Path(f"{out_path}/{filename}")
|
|
46
|
+
exif_dict = None
|
|
47
|
+
if "exif" in img.info:
|
|
48
|
+
exif_dict = piexif.load(img.info["exif"])
|
|
49
|
+
if exif_dict:
|
|
50
|
+
exif_bytes = piexif.dump(exif_dict)
|
|
51
|
+
bd_img.save(out_file, img.format, optimize=True, exif=exif_bytes)
|
|
52
|
+
else:
|
|
53
|
+
bd_img.save(out_file, img.format, optimize=True)
|
|
54
|
+
logger.info(f"Saved {out_file}")
|
|
55
|
+
return True, out_file
|
|
56
|
+
except (AttributeError, FileNotFoundError, ValueError) as e:
|
|
57
|
+
return False, f"{in_path}:\n{e}"
|
|
58
|
+
|
|
59
|
+
@staticmethod
|
|
60
|
+
def add_border_all_in_dir(
|
|
61
|
+
in_path: Path, out_path: Path, border_width: int, border_color: str
|
|
62
|
+
) -> bool:
|
|
63
|
+
"""Add border to all image files in the given dir
|
|
64
|
+
|
|
65
|
+
Args:
|
|
66
|
+
in_path: input dir path
|
|
67
|
+
out_path: output dir path
|
|
68
|
+
border_width: border width int
|
|
69
|
+
border_color: border color str
|
|
70
|
+
|
|
71
|
+
Returns:
|
|
72
|
+
bool: True - Success. False - Error
|
|
73
|
+
"""
|
|
74
|
+
image_files = Common.prepare_all_files(in_path, out_path)
|
|
75
|
+
if not image_files:
|
|
76
|
+
logger.error(f"No image files at {in_path}")
|
|
77
|
+
return False
|
|
78
|
+
tasks = [(f, out_path, border_width, border_color) for f in image_files]
|
|
79
|
+
files_cnt = len(tasks)
|
|
80
|
+
|
|
81
|
+
logger.info(f"Add border to {files_cnt} image files in multiprocess ...")
|
|
82
|
+
success_cnt = Common.multiprocess_progress_bar(
|
|
83
|
+
Border.add_border_1_image, "Add border to image files", tasks
|
|
84
|
+
)
|
|
85
|
+
logger.info(f"\nSuccessfully added border to {success_cnt}/{files_cnt} files")
|
|
86
|
+
return True
|
batch_img/common.py
ADDED
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
"""class Common: common utilities
|
|
2
|
+
Copyright © 2025 John Liu
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import itertools
|
|
6
|
+
import json
|
|
7
|
+
import subprocess
|
|
8
|
+
import tomllib
|
|
9
|
+
from datetime import datetime
|
|
10
|
+
from importlib.metadata import version
|
|
11
|
+
from multiprocessing import Pool, cpu_count
|
|
12
|
+
from os.path import getmtime, getsize
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
import piexif
|
|
16
|
+
import pillow_heif
|
|
17
|
+
from loguru import logger
|
|
18
|
+
from PIL import Image, ImageChops
|
|
19
|
+
from PIL.TiffImagePlugin import IFDRational
|
|
20
|
+
from tqdm import tqdm
|
|
21
|
+
|
|
22
|
+
from batch_img.const import PATTERNS, PKG_NAME, TS_FORMAT, VER
|
|
23
|
+
|
|
24
|
+
pillow_heif.register_heif_opener() # allow Pillow to open HEIC files
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class Common:
|
|
28
|
+
@staticmethod
|
|
29
|
+
def get_version() -> str:
|
|
30
|
+
"""
|
|
31
|
+
Get this package version using several ways
|
|
32
|
+
"""
|
|
33
|
+
try:
|
|
34
|
+
return version(PKG_NAME)
|
|
35
|
+
except (FileNotFoundError, ImportError, ValueError) as e:
|
|
36
|
+
# Use lazy % formatting in logging for efficiency
|
|
37
|
+
logger.warning(f"importlib.metadata.version Error: {e}")
|
|
38
|
+
logger.debug("Try to get version from pyproject.toml file")
|
|
39
|
+
pyproject = Path(__file__).parent.parent / "pyproject.toml"
|
|
40
|
+
with open(pyproject, "rb") as f:
|
|
41
|
+
return tomllib.load(f)["project"][VER]
|
|
42
|
+
|
|
43
|
+
@staticmethod
|
|
44
|
+
def run_cmd(cmd: str) -> tuple:
|
|
45
|
+
"""Run a command on the host and get the output
|
|
46
|
+
|
|
47
|
+
Args:
|
|
48
|
+
cmd (str): a command line with options
|
|
49
|
+
|
|
50
|
+
Returns:
|
|
51
|
+
tuple: returnCode, StdOut, StdErr
|
|
52
|
+
"""
|
|
53
|
+
logger.debug(f"{cmd=}")
|
|
54
|
+
try:
|
|
55
|
+
p = subprocess.run(
|
|
56
|
+
cmd, capture_output=True, text=True, shell=True, check=True
|
|
57
|
+
)
|
|
58
|
+
r_code = p.returncode
|
|
59
|
+
stdout = p.stdout
|
|
60
|
+
stderr = p.stderr
|
|
61
|
+
logger.debug(f"'{cmd}'\n {r_code=}\n {stdout=}\n {stderr=}")
|
|
62
|
+
return r_code, stdout, stderr
|
|
63
|
+
except subprocess.CalledProcessError as e:
|
|
64
|
+
logger.exception(e)
|
|
65
|
+
raise e
|
|
66
|
+
|
|
67
|
+
@staticmethod
|
|
68
|
+
def readable_file_size(in_bytes: int) -> str:
|
|
69
|
+
"""Convert bytes to human-readable KB, MB, or GB
|
|
70
|
+
|
|
71
|
+
Args:
|
|
72
|
+
in_bytes: input bytes integer
|
|
73
|
+
|
|
74
|
+
Returns:
|
|
75
|
+
str
|
|
76
|
+
"""
|
|
77
|
+
for _unit in ["B", "KB", "MB", "GB"]:
|
|
78
|
+
if in_bytes < 1024:
|
|
79
|
+
break
|
|
80
|
+
in_bytes /= 1024
|
|
81
|
+
res = f"{in_bytes} B" if _unit == "B" else f"{in_bytes:.1f} {_unit}"
|
|
82
|
+
return res
|
|
83
|
+
|
|
84
|
+
@staticmethod
|
|
85
|
+
def decode_exif(exif_data: str) -> dict:
|
|
86
|
+
"""Decode the EXIF data
|
|
87
|
+
|
|
88
|
+
Args:
|
|
89
|
+
exif_data: str
|
|
90
|
+
|
|
91
|
+
Returns:
|
|
92
|
+
dict
|
|
93
|
+
"""
|
|
94
|
+
exif_dict = piexif.load(exif_data)
|
|
95
|
+
_dict = {}
|
|
96
|
+
for ifd_name, val in exif_dict.items():
|
|
97
|
+
# Canon EOS 5D Mark II 'thumbnail': b'\xff\xd8\xff\xdb...
|
|
98
|
+
# 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
|
|
99
|
+
if not val or ifd_name == "thumbnail":
|
|
100
|
+
continue
|
|
101
|
+
for tag_id, value in val.items():
|
|
102
|
+
tag_name = piexif.TAGS[ifd_name].get(tag_id, {}).get("name", tag_id)
|
|
103
|
+
_dict[tag_name] = value
|
|
104
|
+
# logger.info(f"{_dict=}")
|
|
105
|
+
for key in (
|
|
106
|
+
"FNumber",
|
|
107
|
+
"FocalLength",
|
|
108
|
+
"MakerNote",
|
|
109
|
+
"SceneType",
|
|
110
|
+
"SubjectArea",
|
|
111
|
+
"Software",
|
|
112
|
+
"HostComputer",
|
|
113
|
+
"UserComment",
|
|
114
|
+
):
|
|
115
|
+
if key in _dict:
|
|
116
|
+
_dict.pop(key)
|
|
117
|
+
keys = list(_dict.keys())
|
|
118
|
+
for keyword in (
|
|
119
|
+
"DateTime",
|
|
120
|
+
"GPS",
|
|
121
|
+
"OffsetTime",
|
|
122
|
+
"SubSecTime",
|
|
123
|
+
"Tile",
|
|
124
|
+
"Pixel",
|
|
125
|
+
"Lens",
|
|
126
|
+
"Resolution",
|
|
127
|
+
"Value",
|
|
128
|
+
):
|
|
129
|
+
for key in keys:
|
|
130
|
+
if key.startswith(keyword) or key.endswith(keyword):
|
|
131
|
+
_dict.pop(key)
|
|
132
|
+
_res = {
|
|
133
|
+
k: (v.decode() if isinstance(v, bytes) else v) for k, v in _dict.items()
|
|
134
|
+
}
|
|
135
|
+
logger.info(f"{_res=}")
|
|
136
|
+
return _res
|
|
137
|
+
|
|
138
|
+
@staticmethod
|
|
139
|
+
def get_image_data(file: Path) -> tuple:
|
|
140
|
+
"""Get image file data
|
|
141
|
+
|
|
142
|
+
Args:
|
|
143
|
+
file: image file path
|
|
144
|
+
|
|
145
|
+
Returns:
|
|
146
|
+
tuple: data, info
|
|
147
|
+
"""
|
|
148
|
+
size = getsize(file)
|
|
149
|
+
m_ts = datetime.fromtimestamp(getmtime(file)).strftime(TS_FORMAT)
|
|
150
|
+
with Image.open(file) as img:
|
|
151
|
+
data = img.convert("RGB")
|
|
152
|
+
d_info = {
|
|
153
|
+
"file_size": Common.readable_file_size(size),
|
|
154
|
+
"file_ts": m_ts,
|
|
155
|
+
"format": img.format,
|
|
156
|
+
"mode": img.mode,
|
|
157
|
+
"size": img.size,
|
|
158
|
+
"info": img.info,
|
|
159
|
+
}
|
|
160
|
+
for key in ("icc_profile", "xmp"):
|
|
161
|
+
if key in img.info:
|
|
162
|
+
img.info.pop(key)
|
|
163
|
+
if "exif" in img.info:
|
|
164
|
+
exif_data = img.info.pop("exif")
|
|
165
|
+
d_info["exif"] = Common.decode_exif(exif_data)
|
|
166
|
+
|
|
167
|
+
return data, d_info
|
|
168
|
+
|
|
169
|
+
@staticmethod
|
|
170
|
+
def jsn_serial(obj):
|
|
171
|
+
"""JSON serializer for objects not serializable by default json code"""
|
|
172
|
+
if isinstance(obj, IFDRational):
|
|
173
|
+
return float(obj)
|
|
174
|
+
if isinstance(obj, bytes):
|
|
175
|
+
return obj.decode()
|
|
176
|
+
raise TypeError(
|
|
177
|
+
f"Object of type {obj.__class__.__name__} is not JSON serializable"
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
@staticmethod
|
|
181
|
+
def are_images_equal(path1: Path, path2: Path) -> bool:
|
|
182
|
+
"""Check if two image files are visually equal pixel-wise
|
|
183
|
+
|
|
184
|
+
Args:
|
|
185
|
+
path1: image1 file path
|
|
186
|
+
path2: image2 file path
|
|
187
|
+
|
|
188
|
+
Returns:
|
|
189
|
+
bool: True - visually equal, False - not visually equal
|
|
190
|
+
"""
|
|
191
|
+
data1, meta1 = Common.get_image_data(path1)
|
|
192
|
+
data2, meta2 = Common.get_image_data(path2)
|
|
193
|
+
|
|
194
|
+
logger.info(
|
|
195
|
+
f"{path1}:\n{json.dumps(meta1, indent=2, default=Common.jsn_serial)}"
|
|
196
|
+
)
|
|
197
|
+
logger.info(
|
|
198
|
+
f"{path2}:\n{json.dumps(meta2, indent=2, default=Common.jsn_serial)}"
|
|
199
|
+
)
|
|
200
|
+
return ImageChops.difference(data1, data2).getbbox() is None
|
|
201
|
+
|
|
202
|
+
@staticmethod
|
|
203
|
+
def get_crop_box(width, height, border_width) -> tuple[float, float, float, float]:
|
|
204
|
+
"""Get the crop box tuple
|
|
205
|
+
|
|
206
|
+
Args:
|
|
207
|
+
width: image width int
|
|
208
|
+
height: image height int
|
|
209
|
+
border_width: border width int
|
|
210
|
+
|
|
211
|
+
Returns:
|
|
212
|
+
tuple[float, float, float, float]
|
|
213
|
+
"""
|
|
214
|
+
crop_left = border_width
|
|
215
|
+
crop_top = border_width
|
|
216
|
+
crop_right = width - border_width
|
|
217
|
+
crop_bottom = height - border_width
|
|
218
|
+
return crop_left, crop_top, crop_right, crop_bottom
|
|
219
|
+
|
|
220
|
+
@staticmethod
|
|
221
|
+
def prepare_all_files(in_path: Path, out_path: Path):
|
|
222
|
+
"""
|
|
223
|
+
|
|
224
|
+
Args:
|
|
225
|
+
in_path: input dir path
|
|
226
|
+
out_path: output dir path
|
|
227
|
+
|
|
228
|
+
Returns:
|
|
229
|
+
iterable: files list generator
|
|
230
|
+
"""
|
|
231
|
+
out_path.mkdir(parents=True, exist_ok=True)
|
|
232
|
+
_files = itertools.chain.from_iterable(in_path.glob(p) for p in PATTERNS)
|
|
233
|
+
return _files
|
|
234
|
+
|
|
235
|
+
@staticmethod
|
|
236
|
+
def multiprocess_progress_bar(func, desc, tasks: list) -> int:
|
|
237
|
+
"""Run task in multiprocess with progress bar
|
|
238
|
+
|
|
239
|
+
Args:
|
|
240
|
+
func: function to be run in multiprocess
|
|
241
|
+
desc: description str
|
|
242
|
+
tasks: tasks list for multiprocess pool
|
|
243
|
+
|
|
244
|
+
Returns:
|
|
245
|
+
int: success_cnt
|
|
246
|
+
"""
|
|
247
|
+
success_cnt = 0
|
|
248
|
+
files_cnt = len(tasks)
|
|
249
|
+
workers = max(cpu_count(), 4)
|
|
250
|
+
|
|
251
|
+
with Pool(workers) as pool:
|
|
252
|
+
with tqdm(total=files_cnt, desc=desc) as pbar:
|
|
253
|
+
for ok, res in pool.starmap(func, tasks):
|
|
254
|
+
if ok:
|
|
255
|
+
success_cnt += 1
|
|
256
|
+
else:
|
|
257
|
+
tqdm.write(f"Error: {res}")
|
|
258
|
+
pbar.update()
|
|
259
|
+
return success_cnt
|
batch_img/const.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""const.py - define constants
|
|
2
|
+
Copyright © 2025 John Liu
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
PKG_NAME = "batch_img"
|
|
6
|
+
VER = "version"
|
|
7
|
+
NAME = "name"
|
|
8
|
+
UNKNOWN = "unknown"
|
|
9
|
+
|
|
10
|
+
MSG_OK = "✅ Processed the image file(s)"
|
|
11
|
+
MSG_BAD = "❌ Failed to process the image file(s)."
|
|
12
|
+
|
|
13
|
+
TS_FORMAT = "%Y-%m-%d_%H-%M-%S"
|
|
14
|
+
PATTERNS = (
|
|
15
|
+
"*.HEIC",
|
|
16
|
+
"*.heic",
|
|
17
|
+
"*.JPG",
|
|
18
|
+
"*.jpg",
|
|
19
|
+
"*.JPEG",
|
|
20
|
+
"*.jpeg",
|
|
21
|
+
"*.PNG",
|
|
22
|
+
"*.png",
|
|
23
|
+
)
|
|
24
|
+
MAX_LENGTH = 1280
|
|
25
|
+
BD_WIDTH = 5
|
|
26
|
+
BD_COLOR = "green"
|
batch_img/defaults.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"""class Defaults: apply default actions to the image file(s):
|
|
2
|
+
* Resize to 1280 pixels as the max length
|
|
3
|
+
* Add the border of 5 pixel width in green color
|
|
4
|
+
* Auto-rotate if upside down or sideways
|
|
5
|
+
Copyright © 2025 John Liu
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
import piexif
|
|
11
|
+
import pillow_heif
|
|
12
|
+
from loguru import logger
|
|
13
|
+
from PIL import Image
|
|
14
|
+
|
|
15
|
+
from batch_img.common import Common
|
|
16
|
+
from batch_img.const import BD_COLOR, BD_WIDTH, MAX_LENGTH
|
|
17
|
+
from batch_img.orientation import Orientation
|
|
18
|
+
from batch_img.rotate import Rotate
|
|
19
|
+
|
|
20
|
+
pillow_heif.register_heif_opener() # allow Pillow to open HEIC files
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class Defaults:
|
|
24
|
+
@staticmethod
|
|
25
|
+
def resize_add_border(in_path: Path, out_path: Path) -> tuple:
|
|
26
|
+
"""Resize and add border to an image file:
|
|
27
|
+
* 1280 as the max length
|
|
28
|
+
* the border of 5-pixel width in green color
|
|
29
|
+
|
|
30
|
+
Args:
|
|
31
|
+
in_path: input file path
|
|
32
|
+
out_path: output dir path
|
|
33
|
+
|
|
34
|
+
Returns:
|
|
35
|
+
tuple: bool, str
|
|
36
|
+
"""
|
|
37
|
+
try:
|
|
38
|
+
with Image.open(in_path) as img:
|
|
39
|
+
# Resize
|
|
40
|
+
max_size = (MAX_LENGTH, MAX_LENGTH)
|
|
41
|
+
img.thumbnail(max_size, Image.Resampling.LANCZOS)
|
|
42
|
+
|
|
43
|
+
# Add border
|
|
44
|
+
width, height = img.size
|
|
45
|
+
logger.info(f"{width=}, {height=}")
|
|
46
|
+
box = Common.get_crop_box(width, height, BD_WIDTH)
|
|
47
|
+
cropped_img = img.crop(box)
|
|
48
|
+
bd_img = Image.new(img.mode, (width, height), BD_COLOR)
|
|
49
|
+
bd_img.paste(cropped_img, (BD_WIDTH, BD_WIDTH))
|
|
50
|
+
|
|
51
|
+
out_path.mkdir(parents=True, exist_ok=True)
|
|
52
|
+
out_file = out_path
|
|
53
|
+
if out_path.is_dir():
|
|
54
|
+
filename = (
|
|
55
|
+
f"{in_path.stem}_{MAX_LENGTH}_bw{BD_WIDTH}{in_path.suffix}"
|
|
56
|
+
)
|
|
57
|
+
out_file = Path(f"{out_path}/{filename}")
|
|
58
|
+
|
|
59
|
+
exif_dict = None
|
|
60
|
+
if "exif" in img.info:
|
|
61
|
+
exif_dict = piexif.load(img.info["exif"])
|
|
62
|
+
if exif_dict:
|
|
63
|
+
exif_bytes = piexif.dump(exif_dict)
|
|
64
|
+
bd_img.save(out_file, img.format, optimize=True, exif=exif_bytes)
|
|
65
|
+
else:
|
|
66
|
+
bd_img.save(out_file, img.format, optimize=True)
|
|
67
|
+
logger.info(f"Saved {out_file}")
|
|
68
|
+
return True, out_file
|
|
69
|
+
except (AttributeError, FileNotFoundError, ValueError) as e:
|
|
70
|
+
return False, f"{in_path}:\n{e}"
|
|
71
|
+
|
|
72
|
+
@staticmethod
|
|
73
|
+
def rotate_if_needed(in_path: Path, out_path: Path) -> tuple:
|
|
74
|
+
"""Rotate if the image is upside down or sideways
|
|
75
|
+
|
|
76
|
+
Args:
|
|
77
|
+
in_path: image file path
|
|
78
|
+
out_path: output dir path
|
|
79
|
+
|
|
80
|
+
Returns:
|
|
81
|
+
tuple: bool, file path
|
|
82
|
+
"""
|
|
83
|
+
# JL 2025-08-18: not get orientation from EXIF as it's unreliable
|
|
84
|
+
# cw_angle = Orientation.exif_orientation_2_cw_angle(in_path)
|
|
85
|
+
# logger.info(f"From exif: {cw_angle=}")
|
|
86
|
+
cw_angle = Orientation().get_cw_angle_by_face(in_path)
|
|
87
|
+
logger.info(f"By face: {cw_angle=}")
|
|
88
|
+
if cw_angle in {-1, 0}:
|
|
89
|
+
logger.warning(f"Skip due to bad or 0 clockwise angle: {cw_angle=}")
|
|
90
|
+
return False, in_path
|
|
91
|
+
ok, out_file = Rotate.rotate_1_image_file(in_path, out_path, cw_angle)
|
|
92
|
+
return ok, out_file
|
|
93
|
+
|
|
94
|
+
@staticmethod
|
|
95
|
+
def do_actions(in_path: Path, out_path: Path) -> tuple:
|
|
96
|
+
"""Do default actions on one image file:
|
|
97
|
+
* Resize to 1280 pixels as the max length
|
|
98
|
+
* Add the border of 5 pixel width in green color
|
|
99
|
+
* Auto-rotate if upside down or sideways
|
|
100
|
+
|
|
101
|
+
Args:
|
|
102
|
+
in_path: input file path
|
|
103
|
+
out_path: output dir path
|
|
104
|
+
|
|
105
|
+
Returns:
|
|
106
|
+
tuple: bool, str
|
|
107
|
+
"""
|
|
108
|
+
_, file = Defaults.rotate_if_needed(in_path, out_path)
|
|
109
|
+
return Defaults.resize_add_border(file, out_path)
|
|
110
|
+
|
|
111
|
+
@staticmethod
|
|
112
|
+
def run_on_all(in_path: Path, out_path: Path) -> bool:
|
|
113
|
+
"""Apply default actions on all images in a folder
|
|
114
|
+
|
|
115
|
+
Args:
|
|
116
|
+
in_path: input file path
|
|
117
|
+
out_path: output dir path
|
|
118
|
+
|
|
119
|
+
Returns:
|
|
120
|
+
bool: True - Success. False - Error
|
|
121
|
+
"""
|
|
122
|
+
image_files = Common.prepare_all_files(in_path, out_path)
|
|
123
|
+
tasks = [(f, out_path) for f in image_files]
|
|
124
|
+
files_cnt = len(tasks)
|
|
125
|
+
if files_cnt == 0:
|
|
126
|
+
logger.error(f"No image files at {in_path}")
|
|
127
|
+
return False
|
|
128
|
+
|
|
129
|
+
logger.info(f"Do default actions on {files_cnt} files in multiprocess ...")
|
|
130
|
+
success_cnt = Common.multiprocess_progress_bar(
|
|
131
|
+
Defaults.do_actions, "Default action on image files", tasks
|
|
132
|
+
)
|
|
133
|
+
logger.info(f"\nFinished default actions on {success_cnt}/{files_cnt} files")
|
|
134
|
+
return True
|
batch_img/interface.py
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
"""interface.py - define CLI interface
|
|
2
|
+
Copyright © 2025 John Liu
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import click
|
|
6
|
+
|
|
7
|
+
from batch_img.common import Common
|
|
8
|
+
from batch_img.const import MSG_BAD, MSG_OK
|
|
9
|
+
from batch_img.main import Main
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@click.group(invoke_without_command=True)
|
|
13
|
+
@click.pass_context
|
|
14
|
+
@click.option("--version", is_flag=True, help="Show this tool's version")
|
|
15
|
+
def cli(ctx, version): # pragma: no cover
|
|
16
|
+
if not ctx.invoked_subcommand:
|
|
17
|
+
if version:
|
|
18
|
+
click.secho(Common.get_version())
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@cli.command(help="Add internal border to image file(s), not expand the size")
|
|
22
|
+
@click.argument(
|
|
23
|
+
"src_path",
|
|
24
|
+
required=True,
|
|
25
|
+
)
|
|
26
|
+
@click.option(
|
|
27
|
+
"-bw",
|
|
28
|
+
"--border_width",
|
|
29
|
+
default=5,
|
|
30
|
+
show_default=True,
|
|
31
|
+
type=click.IntRange(min=0, max=30),
|
|
32
|
+
help="Add border to image file(s) with the border_width. 0 - no border",
|
|
33
|
+
)
|
|
34
|
+
@click.option(
|
|
35
|
+
"-bc",
|
|
36
|
+
"--border_color",
|
|
37
|
+
default="gray",
|
|
38
|
+
show_default=True,
|
|
39
|
+
help="Add border to image file(s) with the border_color string",
|
|
40
|
+
)
|
|
41
|
+
@click.option(
|
|
42
|
+
"-o",
|
|
43
|
+
"--output",
|
|
44
|
+
default="",
|
|
45
|
+
show_default=True,
|
|
46
|
+
type=str,
|
|
47
|
+
help="Output file path. If skipped, use the current dir path",
|
|
48
|
+
)
|
|
49
|
+
def border(src_path, border_width, border_color, output):
|
|
50
|
+
options = {
|
|
51
|
+
"src_path": src_path,
|
|
52
|
+
"border_width": border_width,
|
|
53
|
+
"border_color": border_color,
|
|
54
|
+
"output": output,
|
|
55
|
+
}
|
|
56
|
+
res = Main.border(options)
|
|
57
|
+
msg = MSG_OK if res else MSG_BAD
|
|
58
|
+
click.secho(msg)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@cli.command(
|
|
62
|
+
help="Process image file(s) with default actions:\n"
|
|
63
|
+
"1) resize to 1280; 2) add 5-pixel green color border; 3) auto-rotate if needed"
|
|
64
|
+
)
|
|
65
|
+
@click.argument(
|
|
66
|
+
"src_path",
|
|
67
|
+
required=True,
|
|
68
|
+
)
|
|
69
|
+
@click.option(
|
|
70
|
+
"-o",
|
|
71
|
+
"--output",
|
|
72
|
+
default="",
|
|
73
|
+
show_default=True,
|
|
74
|
+
type=str,
|
|
75
|
+
help="Output file path. If skipped, use the current dir path",
|
|
76
|
+
)
|
|
77
|
+
def defaults(src_path, output):
|
|
78
|
+
"""Do the default action on the image file(s):
|
|
79
|
+
* Resize to 1280 pixels as the max length
|
|
80
|
+
* Add the border of 5 pixel width in green color
|
|
81
|
+
* Auto-rotate if upside down or sideways
|
|
82
|
+
"""
|
|
83
|
+
options = {"src_path": src_path, "output": output}
|
|
84
|
+
res = Main.default_run(options)
|
|
85
|
+
msg = MSG_OK if res else MSG_BAD
|
|
86
|
+
click.secho(msg)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
@cli.command(help="Resize image file(s)")
|
|
90
|
+
@click.argument(
|
|
91
|
+
"src_path",
|
|
92
|
+
required=True,
|
|
93
|
+
)
|
|
94
|
+
@click.option(
|
|
95
|
+
"-l",
|
|
96
|
+
"--length",
|
|
97
|
+
is_flag=False,
|
|
98
|
+
default=0,
|
|
99
|
+
show_default=True,
|
|
100
|
+
type=click.IntRange(min=0),
|
|
101
|
+
help="Resize image file(s) on original aspect ratio to the length. 0 - no resize",
|
|
102
|
+
)
|
|
103
|
+
@click.option(
|
|
104
|
+
"-o",
|
|
105
|
+
"--output",
|
|
106
|
+
default="",
|
|
107
|
+
show_default=True,
|
|
108
|
+
type=str,
|
|
109
|
+
help="Output file path. If skipped, use the current dir path",
|
|
110
|
+
)
|
|
111
|
+
def resize(src_path, length, output):
|
|
112
|
+
options = {"src_path": src_path, "length": length, "output": output}
|
|
113
|
+
res = Main.resize(options)
|
|
114
|
+
msg = MSG_OK if res else MSG_BAD
|
|
115
|
+
click.secho(msg)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
@cli.command(help="Rotate image file(s)")
|
|
119
|
+
@click.argument(
|
|
120
|
+
"src_path",
|
|
121
|
+
required=True,
|
|
122
|
+
)
|
|
123
|
+
@click.option(
|
|
124
|
+
"-a",
|
|
125
|
+
"--angle",
|
|
126
|
+
is_flag=False,
|
|
127
|
+
default=0,
|
|
128
|
+
show_default=True,
|
|
129
|
+
type=click.IntRange(min=0),
|
|
130
|
+
help="Rotate image file(s) to the clockwise angle. 0 - no rotate",
|
|
131
|
+
)
|
|
132
|
+
@click.option(
|
|
133
|
+
"-o",
|
|
134
|
+
"--output",
|
|
135
|
+
default="",
|
|
136
|
+
show_default=True,
|
|
137
|
+
type=str,
|
|
138
|
+
help="Output file path. If skipped, use the current dir path",
|
|
139
|
+
)
|
|
140
|
+
def rotate(src_path, angle, output):
|
|
141
|
+
options = {
|
|
142
|
+
"src_path": src_path,
|
|
143
|
+
"angle": angle,
|
|
144
|
+
"output": output,
|
|
145
|
+
}
|
|
146
|
+
res = Main.rotate(options)
|
|
147
|
+
msg = MSG_OK if res else MSG_BAD
|
|
148
|
+
click.secho(msg)
|
batch_img/main.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
"""class Main: the entry point of the tool
|
|
2
|
+
Copyright © 2025 John Liu
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
from datetime import datetime
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from loguru import logger
|
|
11
|
+
|
|
12
|
+
from batch_img.border import Border
|
|
13
|
+
from batch_img.const import PKG_NAME, TS_FORMAT
|
|
14
|
+
from batch_img.defaults import Defaults
|
|
15
|
+
from batch_img.resize import Resize
|
|
16
|
+
from batch_img.rotate import Rotate
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class Main:
|
|
20
|
+
@staticmethod
|
|
21
|
+
def init_log_file() -> str:
|
|
22
|
+
"""Set up the unique name log file for each run
|
|
23
|
+
|
|
24
|
+
Returns:
|
|
25
|
+
str: log file path
|
|
26
|
+
"""
|
|
27
|
+
log_file = f"run_{PKG_NAME}_{datetime.now().strftime(TS_FORMAT)}.log"
|
|
28
|
+
logger.add(
|
|
29
|
+
f"{os.getcwd()}/{log_file}", backtrace=True, diagnose=True, enqueue=True
|
|
30
|
+
)
|
|
31
|
+
return log_file
|
|
32
|
+
|
|
33
|
+
@staticmethod
|
|
34
|
+
def resize(options: dict) -> bool:
|
|
35
|
+
"""Resize the image file(s)
|
|
36
|
+
|
|
37
|
+
Args:
|
|
38
|
+
options: input options dict
|
|
39
|
+
|
|
40
|
+
Returns:
|
|
41
|
+
bool: True - Success. False - Error
|
|
42
|
+
"""
|
|
43
|
+
logger.info(f"{json.dumps(options, indent=2)}")
|
|
44
|
+
Main.init_log_file()
|
|
45
|
+
in_path = Path(options["src_path"])
|
|
46
|
+
length = options.get("length")
|
|
47
|
+
output = options.get("output")
|
|
48
|
+
if not length or length == 0:
|
|
49
|
+
logger.warning(f"No resize due to bad {length=}")
|
|
50
|
+
return False
|
|
51
|
+
if not output:
|
|
52
|
+
output = Path(os.getcwd())
|
|
53
|
+
else:
|
|
54
|
+
output = Path(output)
|
|
55
|
+
if in_path.is_file():
|
|
56
|
+
ok, _ = Resize.resize_an_image(in_path, output, length)
|
|
57
|
+
else:
|
|
58
|
+
ok = Resize.resize_all_progress_bar(in_path, output, length)
|
|
59
|
+
return ok
|
|
60
|
+
|
|
61
|
+
@staticmethod
|
|
62
|
+
def rotate(options: dict) -> bool:
|
|
63
|
+
"""Rotate the image file(s)
|
|
64
|
+
|
|
65
|
+
Args:
|
|
66
|
+
options: input options dict
|
|
67
|
+
|
|
68
|
+
Returns:
|
|
69
|
+
bool: True - Success. False - Error
|
|
70
|
+
"""
|
|
71
|
+
logger.info(f"{json.dumps(options, indent=2)}")
|
|
72
|
+
Main.init_log_file()
|
|
73
|
+
in_path = Path(options["src_path"])
|
|
74
|
+
angle = options.get("angle")
|
|
75
|
+
output = options.get("output")
|
|
76
|
+
if not angle or angle == 0:
|
|
77
|
+
logger.warning(f"No rotate due to bad {angle=}")
|
|
78
|
+
return False
|
|
79
|
+
if not output:
|
|
80
|
+
output = Path(os.getcwd())
|
|
81
|
+
else:
|
|
82
|
+
output = Path(output)
|
|
83
|
+
if in_path.is_file():
|
|
84
|
+
ok, _ = Rotate.rotate_1_image_file(in_path, output, angle)
|
|
85
|
+
else:
|
|
86
|
+
ok = Rotate.rotate_all_in_dir(in_path, output, angle)
|
|
87
|
+
return ok
|
|
88
|
+
|
|
89
|
+
@staticmethod
|
|
90
|
+
def border(options: dict) -> bool:
|
|
91
|
+
"""Add border to the image file(s)
|
|
92
|
+
|
|
93
|
+
Args:
|
|
94
|
+
options: input options dict
|
|
95
|
+
|
|
96
|
+
Returns:
|
|
97
|
+
bool: True - Success. False - Error
|
|
98
|
+
"""
|
|
99
|
+
logger.info(f"{json.dumps(options, indent=2)}")
|
|
100
|
+
Main.init_log_file()
|
|
101
|
+
in_path = Path(options["src_path"])
|
|
102
|
+
bd_width = options.get("border_width")
|
|
103
|
+
bd_color = options.get("border_color")
|
|
104
|
+
output = options.get("output")
|
|
105
|
+
if not bd_width or bd_width == 0:
|
|
106
|
+
logger.warning(f"No add border due to bad {bd_width=}")
|
|
107
|
+
return False
|
|
108
|
+
if not output:
|
|
109
|
+
output = Path(os.getcwd())
|
|
110
|
+
else:
|
|
111
|
+
output = Path(output)
|
|
112
|
+
if in_path.is_file():
|
|
113
|
+
ok, _ = Border.add_border_1_image(in_path, output, bd_width, bd_color)
|
|
114
|
+
else:
|
|
115
|
+
ok = Border.add_border_all_in_dir(in_path, output, bd_width, bd_color)
|
|
116
|
+
return ok
|
|
117
|
+
|
|
118
|
+
@staticmethod
|
|
119
|
+
def default_run(options: dict) -> bool:
|
|
120
|
+
"""Do the default action on the image file(s):
|
|
121
|
+
* Resize to 1280 pixels as the max length
|
|
122
|
+
* Add the border of 5 pixel width in green color
|
|
123
|
+
* Auto-rotate if upside down or sideways
|
|
124
|
+
"""
|
|
125
|
+
logger.info(f"{json.dumps(options, indent=2)}")
|
|
126
|
+
Main.init_log_file()
|
|
127
|
+
in_path = Path(options["src_path"])
|
|
128
|
+
output = options.get("output")
|
|
129
|
+
if not output:
|
|
130
|
+
output = Path(os.getcwd())
|
|
131
|
+
else:
|
|
132
|
+
output = Path(output)
|
|
133
|
+
if in_path.is_file():
|
|
134
|
+
ok, _ = Defaults.do_actions(in_path, output)
|
|
135
|
+
else:
|
|
136
|
+
ok = Defaults.run_on_all(in_path, output)
|
|
137
|
+
return ok
|
batch_img/orientation.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"""class Orientation: detect if the image file(s) is upside down or sideways
|
|
2
|
+
Copyright © 2025 John Liu
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
import cv2
|
|
8
|
+
import numpy as np
|
|
9
|
+
import pillow_heif
|
|
10
|
+
from loguru import logger
|
|
11
|
+
from PIL import Image
|
|
12
|
+
|
|
13
|
+
from batch_img.common import Common
|
|
14
|
+
|
|
15
|
+
pillow_heif.register_heif_opener() # allow Pillow to open HEIC files
|
|
16
|
+
|
|
17
|
+
ORIENTATION_MAP = {
|
|
18
|
+
1: "normal",
|
|
19
|
+
2: "mirrored_horizontal",
|
|
20
|
+
3: "upside_down",
|
|
21
|
+
4: "mirrored_vertical",
|
|
22
|
+
5: "rotated_left_mirrored",
|
|
23
|
+
6: "rotated_left",
|
|
24
|
+
7: "rotated_right_mirrored",
|
|
25
|
+
8: "rotated_right",
|
|
26
|
+
}
|
|
27
|
+
EXIF_CW_ANGLE = {
|
|
28
|
+
1: 0,
|
|
29
|
+
2: 0,
|
|
30
|
+
3: 180,
|
|
31
|
+
4: 180,
|
|
32
|
+
5: 270,
|
|
33
|
+
6: 270,
|
|
34
|
+
7: 90,
|
|
35
|
+
8: 90,
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class Orientation:
|
|
40
|
+
@staticmethod
|
|
41
|
+
def exif_orientation_2_cw_angle(file: Path) -> int:
|
|
42
|
+
"""Get image orientation by EXIF data
|
|
43
|
+
|
|
44
|
+
Args:
|
|
45
|
+
file: image file path
|
|
46
|
+
|
|
47
|
+
Returns:
|
|
48
|
+
int: clockwise angle: 0, 90, 180, 270
|
|
49
|
+
"""
|
|
50
|
+
try:
|
|
51
|
+
with Image.open(file) as img:
|
|
52
|
+
if "exif" not in img.info:
|
|
53
|
+
logger.warning(f"No EXIF data in {file}")
|
|
54
|
+
return -1
|
|
55
|
+
exif_info = Common.decode_exif(img.info["exif"])
|
|
56
|
+
if "Orientation" in exif_info:
|
|
57
|
+
return EXIF_CW_ANGLE.get(exif_info["Orientation"])
|
|
58
|
+
logger.warning(f"No 'Orientation' tag in {exif_info=}")
|
|
59
|
+
return -1
|
|
60
|
+
except (AttributeError, FileNotFoundError, ValueError) as e:
|
|
61
|
+
logger.error(e)
|
|
62
|
+
return -1
|
|
63
|
+
|
|
64
|
+
@staticmethod
|
|
65
|
+
def _rotate_image(img, angle: int):
|
|
66
|
+
"""Helper to rotate image by the clock wise angle degree
|
|
67
|
+
|
|
68
|
+
Args:
|
|
69
|
+
img: image data
|
|
70
|
+
angle: angle degree int: 0, 90, 180, 270
|
|
71
|
+
|
|
72
|
+
Returns:
|
|
73
|
+
image data
|
|
74
|
+
"""
|
|
75
|
+
if angle == 90:
|
|
76
|
+
return cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE)
|
|
77
|
+
if angle == 180:
|
|
78
|
+
return cv2.rotate(img, cv2.ROTATE_180)
|
|
79
|
+
if angle == 270:
|
|
80
|
+
return cv2.rotate(img, cv2.ROTATE_90_COUNTERCLOCKWISE)
|
|
81
|
+
return img
|
|
82
|
+
|
|
83
|
+
def get_cw_angle_by_face(self, file: Path) -> int:
|
|
84
|
+
"""Detect orientation by face in mage by Haar Cascades:
|
|
85
|
+
* Fastest but least accurate
|
|
86
|
+
* Works best with frontal faces
|
|
87
|
+
* May produce false positives
|
|
88
|
+
|
|
89
|
+
Args:
|
|
90
|
+
file: image file path
|
|
91
|
+
|
|
92
|
+
Returns:
|
|
93
|
+
int: clockwise angle: 0, 90, 180, 270
|
|
94
|
+
"""
|
|
95
|
+
face_cascade = cv2.CascadeClassifier(
|
|
96
|
+
cv2.data.haarcascades + "haarcascade_frontalface_default.xml"
|
|
97
|
+
)
|
|
98
|
+
with Image.open(file) as safe_img:
|
|
99
|
+
opencv_img = np.array(safe_img)
|
|
100
|
+
if opencv_img is None:
|
|
101
|
+
raise ValueError(f"Failed to load {file}")
|
|
102
|
+
for angle_cw in (0, 90, 180, 270):
|
|
103
|
+
img = self._rotate_image(opencv_img, angle_cw)
|
|
104
|
+
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
|
105
|
+
faces = face_cascade.detectMultiScale(
|
|
106
|
+
gray, scaleFactor=1.2, minNeighbors=6
|
|
107
|
+
)
|
|
108
|
+
# logger.info(f"{len(faces)=}")
|
|
109
|
+
if len(faces) > 0:
|
|
110
|
+
return angle_cw
|
|
111
|
+
logger.warning(f"Found no face in {file}")
|
|
112
|
+
return -1
|
batch_img/resize.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""class Resize: resize the image file(s)
|
|
2
|
+
Copyright © 2025 John Liu
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
import piexif
|
|
8
|
+
import pillow_heif
|
|
9
|
+
from loguru import logger
|
|
10
|
+
from PIL import Image
|
|
11
|
+
|
|
12
|
+
from batch_img.common import Common
|
|
13
|
+
|
|
14
|
+
pillow_heif.register_heif_opener() # allow Pillow to open HEIC files
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class Resize:
|
|
18
|
+
@staticmethod
|
|
19
|
+
def resize_an_image(in_path: Path, out_path: Path, length: int) -> tuple:
|
|
20
|
+
"""Resize an image file and save to the output dir
|
|
21
|
+
|
|
22
|
+
Args:
|
|
23
|
+
in_path: input file path
|
|
24
|
+
out_path: output dir path
|
|
25
|
+
length: max length (width or height) in pixels
|
|
26
|
+
|
|
27
|
+
Returns:
|
|
28
|
+
tuple: bool, output file path
|
|
29
|
+
"""
|
|
30
|
+
try:
|
|
31
|
+
with Image.open(in_path) as img:
|
|
32
|
+
max_size = (length, length)
|
|
33
|
+
# The thumbnail() keeps the original aspect ratio
|
|
34
|
+
img.thumbnail(max_size, Image.Resampling.LANCZOS)
|
|
35
|
+
|
|
36
|
+
out_path.mkdir(parents=True, exist_ok=True)
|
|
37
|
+
out_file = out_path
|
|
38
|
+
if out_path.is_dir():
|
|
39
|
+
filename = f"{in_path.stem}_{length}{in_path.suffix}"
|
|
40
|
+
out_file = Path(f"{out_path}/{filename}")
|
|
41
|
+
|
|
42
|
+
exif_dict = None
|
|
43
|
+
if "exif" in img.info:
|
|
44
|
+
exif_dict = piexif.load(img.info["exif"])
|
|
45
|
+
if exif_dict:
|
|
46
|
+
exif_bytes = piexif.dump(exif_dict)
|
|
47
|
+
img.save(out_file, img.format, optimize=True, exif=exif_bytes)
|
|
48
|
+
else:
|
|
49
|
+
img.save(out_file, img.format, optimize=True)
|
|
50
|
+
logger.info(f"Saved {out_file}")
|
|
51
|
+
return True, out_file
|
|
52
|
+
except (AttributeError, FileNotFoundError, ValueError) as e:
|
|
53
|
+
return False, f"{in_path}:\n{e}"
|
|
54
|
+
|
|
55
|
+
@staticmethod
|
|
56
|
+
def resize_all_progress_bar(in_path: Path, out_path: Path, length: int) -> bool:
|
|
57
|
+
"""Resize all image files in the given dir
|
|
58
|
+
|
|
59
|
+
Args:
|
|
60
|
+
in_path: input dir path
|
|
61
|
+
out_path: output dir path
|
|
62
|
+
length: max length (width or height) in pixels
|
|
63
|
+
|
|
64
|
+
Returns:
|
|
65
|
+
bool: True - Success. False - Error
|
|
66
|
+
"""
|
|
67
|
+
image_files = Common.prepare_all_files(in_path, out_path)
|
|
68
|
+
if not image_files:
|
|
69
|
+
logger.error(f"No image files at {in_path}")
|
|
70
|
+
return False
|
|
71
|
+
tasks = [(f, out_path, length) for f in image_files]
|
|
72
|
+
files_cnt = len(tasks)
|
|
73
|
+
|
|
74
|
+
logger.info(f"Resize {files_cnt} image files in multiprocess ...")
|
|
75
|
+
success_cnt = Common.multiprocess_progress_bar(
|
|
76
|
+
Resize.resize_an_image, "Resize image files", tasks
|
|
77
|
+
)
|
|
78
|
+
logger.info(f"\nSuccessfully resized {success_cnt}/{files_cnt} files")
|
|
79
|
+
return True
|
batch_img/rotate.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"""class Rotate: rotate image file(s) to clockwise angle
|
|
2
|
+
Copyright © 2025 John Liu
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
import piexif
|
|
9
|
+
import pillow_heif
|
|
10
|
+
from loguru import logger
|
|
11
|
+
from PIL import Image
|
|
12
|
+
|
|
13
|
+
from batch_img.common import Common
|
|
14
|
+
|
|
15
|
+
pillow_heif.register_heif_opener() # allow Pillow to open HEIC files
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class Rotate:
|
|
19
|
+
@staticmethod
|
|
20
|
+
def set_exif_orientation(file: Path, o_val: int) -> bool:
|
|
21
|
+
"""Set orientation in the EXIF of an image file
|
|
22
|
+
|
|
23
|
+
Args:
|
|
24
|
+
file: image file path
|
|
25
|
+
o_val: orientation value int
|
|
26
|
+
|
|
27
|
+
Returns:
|
|
28
|
+
bool: True - Success. False - Error
|
|
29
|
+
"""
|
|
30
|
+
if o_val not in {1, 2, 3, 4, 5, 6, 7, 8}:
|
|
31
|
+
logger.error(f"Quit due to bad orientation value: {o_val=}")
|
|
32
|
+
return False
|
|
33
|
+
try:
|
|
34
|
+
tmp_file = Path(f"{file.parent}/{file.stem}_tmp{file.suffix}")
|
|
35
|
+
with Image.open(file) as img:
|
|
36
|
+
exif_dict = {"0th": {}, "Exif": {}}
|
|
37
|
+
if "exif" in img.info:
|
|
38
|
+
exif_dict = piexif.load(img.info["exif"])
|
|
39
|
+
exif_dict["0th"][piexif.ImageIFD.Orientation] = o_val
|
|
40
|
+
exif_bytes = piexif.dump(exif_dict)
|
|
41
|
+
img.save(tmp_file, img.format, exif=exif_bytes, optimize=True)
|
|
42
|
+
logger.info(f"Saved the updated EXIF image to {tmp_file}")
|
|
43
|
+
os.replace(tmp_file, file)
|
|
44
|
+
logger.info(f"Replaced {file} with tmp_file")
|
|
45
|
+
return True
|
|
46
|
+
except (AttributeError, FileNotFoundError, ValueError) as e:
|
|
47
|
+
logger.error(e)
|
|
48
|
+
return False
|
|
49
|
+
|
|
50
|
+
@staticmethod
|
|
51
|
+
def rotate_1_image_file(in_path: Path, out_path: Path, angle_cw: int) -> tuple:
|
|
52
|
+
"""Rotate an image file and save to the output dir
|
|
53
|
+
|
|
54
|
+
Args:
|
|
55
|
+
in_path: input file path
|
|
56
|
+
out_path: output dir path
|
|
57
|
+
angle_cw: rotation angle clockwise: 90, 180, or 270
|
|
58
|
+
|
|
59
|
+
Returns:
|
|
60
|
+
tuple: bool, str
|
|
61
|
+
"""
|
|
62
|
+
if angle_cw not in {90, 180, 270}:
|
|
63
|
+
return False, f"Bad {angle_cw=}. Only allow 90, 180, 270"
|
|
64
|
+
try:
|
|
65
|
+
with Image.open(in_path) as img:
|
|
66
|
+
exif_dict = {"0th": {}, "Exif": {}}
|
|
67
|
+
if "exif" in img.info:
|
|
68
|
+
exif_dict = piexif.load(img.info["exif"])
|
|
69
|
+
# logger.info(f"{exif_dict=}")
|
|
70
|
+
exif_dict["0th"][piexif.ImageIFD.Orientation] = 1
|
|
71
|
+
exif_bytes = piexif.dump(exif_dict)
|
|
72
|
+
|
|
73
|
+
out_path.mkdir(parents=True, exist_ok=True)
|
|
74
|
+
out_file = out_path
|
|
75
|
+
if out_path.is_dir():
|
|
76
|
+
filename = f"{in_path.stem}_{angle_cw}cw{in_path.suffix}"
|
|
77
|
+
out_file = Path(f"{out_path}/{filename}")
|
|
78
|
+
# img.rotate() for any angle (slower & slight quality loss)
|
|
79
|
+
if angle_cw == 90:
|
|
80
|
+
rotated_img = img.transpose(Image.ROTATE_270)
|
|
81
|
+
elif angle_cw == 180:
|
|
82
|
+
rotated_img = img.transpose(Image.ROTATE_180)
|
|
83
|
+
elif angle_cw == 270:
|
|
84
|
+
rotated_img = img.transpose(Image.ROTATE_90)
|
|
85
|
+
else:
|
|
86
|
+
rotated_img = img
|
|
87
|
+
|
|
88
|
+
rotated_img.save(out_file, img.format, exif=exif_bytes, optimize=True)
|
|
89
|
+
logger.info(f"Saved ({angle_cw}°) clockwise rotated to {out_file}")
|
|
90
|
+
return True, out_file
|
|
91
|
+
except (AttributeError, FileNotFoundError, ValueError) as e:
|
|
92
|
+
return False, f"{in_path}:\n{e}"
|
|
93
|
+
|
|
94
|
+
@staticmethod
|
|
95
|
+
def rotate_all_in_dir(in_path: Path, out_path: Path, angle_cw: int) -> bool:
|
|
96
|
+
"""Rotate all image files in the given dir
|
|
97
|
+
|
|
98
|
+
Args:
|
|
99
|
+
in_path: input dir path
|
|
100
|
+
out_path: output dir path
|
|
101
|
+
angle_cw: rotation angle clockwise: 90, 180, or 270
|
|
102
|
+
|
|
103
|
+
Returns:
|
|
104
|
+
bool: True - Success. False - Error
|
|
105
|
+
"""
|
|
106
|
+
if angle_cw not in {90, 180, 270}:
|
|
107
|
+
logger.error(f"Bad {angle_cw=}. Only allow 90, 180, 270")
|
|
108
|
+
return False
|
|
109
|
+
image_files = Common.prepare_all_files(in_path, out_path)
|
|
110
|
+
if not image_files:
|
|
111
|
+
logger.error(f"No image files at {in_path}")
|
|
112
|
+
return False
|
|
113
|
+
tasks = [(f, out_path, angle_cw) for f in image_files]
|
|
114
|
+
files_cnt = len(tasks)
|
|
115
|
+
|
|
116
|
+
logger.info(f"Rotate {files_cnt} image files in multiprocess ...")
|
|
117
|
+
success_cnt = Common.multiprocess_progress_bar(
|
|
118
|
+
Rotate.rotate_1_image_file, "Rotate image files", tasks
|
|
119
|
+
)
|
|
120
|
+
logger.info(f"\nSuccessfully rotated {success_cnt}/{files_cnt} files")
|
|
121
|
+
return True
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: batch_img
|
|
3
|
+
Version: 0.0.7
|
|
4
|
+
Summary: Batch processing image files by utilizing Pillow / PIL library
|
|
5
|
+
Author: John Liu
|
|
6
|
+
Project-URL: Download, https://artifacts.some.where
|
|
7
|
+
Project-URL: Homepage, https://github.com/john-liu2/batch_img
|
|
8
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
9
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
11
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Requires-Python: >=3.12
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
License-File: LICENSE
|
|
16
|
+
Requires-Dist: click
|
|
17
|
+
Requires-Dist: loguru
|
|
18
|
+
Requires-Dist: piexif
|
|
19
|
+
Requires-Dist: pillow
|
|
20
|
+
Requires-Dist: pillow-heif
|
|
21
|
+
Requires-Dist: tqdm
|
|
22
|
+
Requires-Dist: numpy
|
|
23
|
+
Requires-Dist: opencv-python
|
|
24
|
+
Dynamic: license-file
|
|
25
|
+
|
|
26
|
+
## batch_img
|
|
27
|
+
|
|
28
|
+
Batch processing image files by utilizing **[Pillow / PIL](https://github.com/python-pillow/Pillow)** library.
|
|
29
|
+
Resize, rotate, add border or do default actions on a single image file or all image files in a folder.
|
|
30
|
+
Tested these image file formats (**HEIC, JPG, PNG**) on macOS.
|
|
31
|
+
|
|
32
|
+
### Installation
|
|
33
|
+
|
|
34
|
+
#### One Time Setup
|
|
35
|
+
|
|
36
|
+
One time installation of the `uv` tool to prepare for **All** future Python tools installation.
|
|
37
|
+
Install `uv` tool by its standalone installers:
|
|
38
|
+
|
|
39
|
+
```
|
|
40
|
+
# On macOS and Linux.
|
|
41
|
+
curl -LsSf https://astral.sh/uv/install.sh | sh
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
```
|
|
45
|
+
# On Windows.
|
|
46
|
+
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
#### Install the `batch_img` tool
|
|
50
|
+
|
|
51
|
+
Install the `batch_img` tool from PyPI:
|
|
52
|
+
|
|
53
|
+
```
|
|
54
|
+
uv pip install --upgrade batch_img
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
### Usage
|
|
58
|
+
|
|
59
|
+
#### Sample command lines:
|
|
60
|
+
|
|
61
|
+
```
|
|
62
|
+
✗ batch_img --version
|
|
63
|
+
0.0.7
|
|
64
|
+
|
|
65
|
+
✗ batch_img rotate --degree 90 ~/Downloads/IMG_0070.HEIC
|
|
66
|
+
...
|
|
67
|
+
✅ Processed the image file(s)
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
### Help
|
|
71
|
+
|
|
72
|
+
#### Top level commands help:
|
|
73
|
+
|
|
74
|
+
```
|
|
75
|
+
✗ batch_img --help
|
|
76
|
+
Usage: batch_img [OPTIONS] COMMAND [ARGS]...
|
|
77
|
+
|
|
78
|
+
Options:
|
|
79
|
+
--version Show this tool's version
|
|
80
|
+
--help Show this message and exit.
|
|
81
|
+
|
|
82
|
+
Commands:
|
|
83
|
+
border Add border to image file(s)
|
|
84
|
+
defaults Process image file(s) with default actions: 1) resize to...
|
|
85
|
+
resize Resize image file(s)
|
|
86
|
+
rotate Rotate image file(s)
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
#### The `border` sub-command CLI options:
|
|
90
|
+
|
|
91
|
+
```
|
|
92
|
+
✗ batch_img border --help
|
|
93
|
+
Usage: batch_img border [OPTIONS] SRC_PATH
|
|
94
|
+
|
|
95
|
+
Add internal border to image file(s), not expand the size
|
|
96
|
+
|
|
97
|
+
Options:
|
|
98
|
+
-bw, --border_width INTEGER RANGE
|
|
99
|
+
Add border to image file(s) with the
|
|
100
|
+
border_width. 0 - no border [default: 5;
|
|
101
|
+
0<=x<=30]
|
|
102
|
+
-bc, --border_color TEXT Add border to image file(s) with the
|
|
103
|
+
border_color string [default: gray]
|
|
104
|
+
-o, --output TEXT Output file path. If skipped, use the
|
|
105
|
+
current dir path [default: ""]
|
|
106
|
+
--help Show this message and exit.
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
#### The `defaults` sub-command CLI options:
|
|
110
|
+
|
|
111
|
+
```
|
|
112
|
+
✗ batch_img defaults --help
|
|
113
|
+
Usage: batch_img defaults [OPTIONS] SRC_PATH
|
|
114
|
+
|
|
115
|
+
Process image file(s) with default actions: 1) resize to 1280; 2) add
|
|
116
|
+
5-pixel gray color border; 3) auto-rotate if needed
|
|
117
|
+
|
|
118
|
+
Options:
|
|
119
|
+
-o, --output TEXT Output file path. If skipped, use the current dir path
|
|
120
|
+
[default: ""]
|
|
121
|
+
--help Show this message and exit.
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
#### The `resize` sub-command CLI options:
|
|
125
|
+
|
|
126
|
+
```
|
|
127
|
+
✗ batch_img resize --help
|
|
128
|
+
Usage: batch_img resize [OPTIONS] SRC_PATH
|
|
129
|
+
|
|
130
|
+
Resize image file(s)
|
|
131
|
+
|
|
132
|
+
Options:
|
|
133
|
+
-l, --length INTEGER RANGE Resize image file(s) on original aspect ratio to
|
|
134
|
+
the length. 0 - no resize [default: 0; x>=0]
|
|
135
|
+
-o, --output TEXT Output file path. If skipped, use the current
|
|
136
|
+
dir path [default: ""]
|
|
137
|
+
--help Show this message and exit.
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
#### The `rotate` sub-command CLI options:
|
|
141
|
+
|
|
142
|
+
```
|
|
143
|
+
✗ batch_img rotate --help
|
|
144
|
+
Usage: batch_img rotate [OPTIONS] SRC_PATH
|
|
145
|
+
|
|
146
|
+
Rotate image file(s)
|
|
147
|
+
|
|
148
|
+
Options:
|
|
149
|
+
-a, --angle INTEGER RANGE Rotate image file(s) to the clockwise angle. 0 -
|
|
150
|
+
no rotate [default: 0; x>=0]
|
|
151
|
+
-o, --output TEXT Output file path. If skipped, use the current dir
|
|
152
|
+
path [default: ""]
|
|
153
|
+
--help Show this message and exit.
|
|
154
|
+
```
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
batch_img/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
2
|
+
batch_img/border.py,sha256=BrdyiKPkIkVnXKamxiWsnkh0PdF466NfwULjCj38A_g,3058
|
|
3
|
+
batch_img/common.py,sha256=M-uTuEwTcOw2CKEyGHJdKGsnyZUf08bFcxLfuIser3Q,7847
|
|
4
|
+
batch_img/const.py,sha256=gy5DtaMdsV8EivfBHOI-Ur1swZU8zrKailpwLYd5e6M,439
|
|
5
|
+
batch_img/defaults.py,sha256=SoImENWwfrReu_WxE7EPZlNsBAzm9MkRrX6wzkqfE74,4782
|
|
6
|
+
batch_img/interface.py,sha256=4mLLAulzOYhUBA_f22mqcggHKMYqHeiLPvyKO60t7oo,3577
|
|
7
|
+
batch_img/main.py,sha256=TGk9KQSNaq4K_571AVW4ydA5R54iCZ_cJREKKkFDyUg,4215
|
|
8
|
+
batch_img/orientation.py,sha256=dRxN5gqGeyn6Ch4g3Bzi2TyyIaRb4YC6EDpZsJwwPKk,3243
|
|
9
|
+
batch_img/resize.py,sha256=KyUZSTEsHEqt_TVlOleGEIFf_Pq-j2ZejBXNVyiOxV8,2725
|
|
10
|
+
batch_img/rotate.py,sha256=wFv0gCmqFOjzThVLgTjCWb5rLQrQKE3SdvdyN7To81Y,4579
|
|
11
|
+
batch_img-0.0.7.dist-info/licenses/LICENSE,sha256=2IE5k441iviLxA3Qx_pNq7f1SFbLLxT6oC5EXaGC0gY,1065
|
|
12
|
+
batch_img-0.0.7.dist-info/METADATA,sha256=E7oDGQwsdjNhttKu4B_Pd5EEtMySOnKNJQZJEhdTx80,4326
|
|
13
|
+
batch_img-0.0.7.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
14
|
+
batch_img-0.0.7.dist-info/entry_points.txt,sha256=o7E04t_Y7i9wcd4YMjJBKR5l0pnOaU-HiuHMf3s5Ds4,54
|
|
15
|
+
batch_img-0.0.7.dist-info/top_level.txt,sha256=KUBx0Cw8yaA0XQMJf3yf0pJDm-5ojMMQtG7k1A9kYz8,10
|
|
16
|
+
batch_img-0.0.7.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 John Liu
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
batch_img
|