imgbytesizer 0.2.0__tar.gz → 0.2.2__tar.gz
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.
- {imgbytesizer-0.2.0 → imgbytesizer-0.2.2}/PKG-INFO +27 -18
- {imgbytesizer-0.2.0 → imgbytesizer-0.2.2}/README.md +26 -17
- imgbytesizer-0.2.2/imgbytesizer/__init__.py +7 -0
- imgbytesizer-0.2.2/imgbytesizer/formatter.py +18 -0
- imgbytesizer-0.2.2/imgbytesizer/logger.py +206 -0
- imgbytesizer-0.2.2/imgbytesizer/main.py +104 -0
- imgbytesizer-0.2.2/imgbytesizer/resizer.py +547 -0
- imgbytesizer-0.2.2/imgbytesizer/utils.py +106 -0
- {imgbytesizer-0.2.0 → imgbytesizer-0.2.2}/imgbytesizer.egg-info/PKG-INFO +27 -18
- {imgbytesizer-0.2.0 → imgbytesizer-0.2.2}/imgbytesizer.egg-info/SOURCES.txt +6 -2
- {imgbytesizer-0.2.0 → imgbytesizer-0.2.2}/pyproject.toml +1 -1
- {imgbytesizer-0.2.0 → imgbytesizer-0.2.2}/setup.cfg +0 -3
- imgbytesizer-0.2.2/tests/test_formatter.py +16 -0
- imgbytesizer-0.2.2/tests/test_logger.py +48 -0
- imgbytesizer-0.2.2/tests/test_main.py +128 -0
- imgbytesizer-0.2.2/tests/test_resizer.py +291 -0
- imgbytesizer-0.2.2/tests/test_utils.py +99 -0
- imgbytesizer-0.2.0/imgbytesizer/__init__.py +0 -7
- imgbytesizer-0.2.0/imgbytesizer/formatter.py +0 -162
- imgbytesizer-0.2.0/imgbytesizer/logger.py +0 -55
- imgbytesizer-0.2.0/imgbytesizer/main.py +0 -112
- imgbytesizer-0.2.0/imgbytesizer/resizer.py +0 -552
- imgbytesizer-0.2.0/imgbytesizer/utils.py +0 -100
- {imgbytesizer-0.2.0 → imgbytesizer-0.2.2}/LICENSE +0 -0
- {imgbytesizer-0.2.0 → imgbytesizer-0.2.2}/imgbytesizer.egg-info/dependency_links.txt +0 -0
- {imgbytesizer-0.2.0 → imgbytesizer-0.2.2}/imgbytesizer.egg-info/entry_points.txt +0 -0
- {imgbytesizer-0.2.0 → imgbytesizer-0.2.2}/imgbytesizer.egg-info/requires.txt +0 -0
- {imgbytesizer-0.2.0 → imgbytesizer-0.2.2}/imgbytesizer.egg-info/top_level.txt +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: imgbytesizer
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.2
|
|
4
4
|
Summary: A CLI tool to resize images to a target file size.
|
|
5
5
|
Author-email: pyyupsk <contact@fasu.dev>
|
|
6
6
|
License: MIT License
|
|
@@ -16,6 +16,7 @@ Dynamic: license-file
|
|
|
16
16
|
|
|
17
17
|
[](https://pypi.org/project/imgbytesizer/)
|
|
18
18
|
[](https://pepy.tech/projects/imgbytesizer)
|
|
19
|
+
[](https://codecov.io/gh/pyyupsk/imgbytesizer)
|
|
19
20
|
|
|
20
21
|
ImgByteSizer is a command-line tool that precisely resizes and optimizes images to match a specific file size while maintaining the best possible quality.
|
|
21
22
|
|
|
@@ -48,7 +49,7 @@ imgbytesizer image.jpg 500KB
|
|
|
48
49
|
imgbytesizer large_photo.jpg 500KB
|
|
49
50
|
|
|
50
51
|
# Resize and convert to WebP format
|
|
51
|
-
imgbytesizer image.png
|
|
52
|
+
imgbytesizer image.png 1MB -f webp
|
|
52
53
|
|
|
53
54
|
# Specify output file path
|
|
54
55
|
imgbytesizer photo.jpg 1MB -o compressed_photo.jpg
|
|
@@ -95,37 +96,45 @@ The tool prioritizes maintaining the highest possible quality while meeting the
|
|
|
95
96
|
## Example Output
|
|
96
97
|
|
|
97
98
|
```
|
|
99
|
+
❯ imgbytesizer image.png 1MB -f webp
|
|
100
|
+
|
|
98
101
|
◐ Opening image.png
|
|
99
102
|
File: image.png
|
|
100
103
|
Format: WEBP
|
|
101
|
-
Dimensions:
|
|
102
|
-
Size: 1.
|
|
103
|
-
Target size:
|
|
104
|
+
Dimensions: 1024 × 1024 pixels
|
|
105
|
+
Size: 1.95 MB
|
|
106
|
+
Target size: 1.00 MB
|
|
104
107
|
Trying quality adjustment without resizing...
|
|
105
|
-
Testing quality
|
|
106
|
-
✓ Found optimal quality:
|
|
108
|
+
Testing quality 100 |█████████████████░░░░░░░░░░░░░| 58% Size: 476.46 KB
|
|
109
|
+
✓ Found optimal quality: 100 (size: 476.46 KB)
|
|
110
|
+
Trying combined scaling and quality approach...
|
|
111
|
+
Trying scale factor 1.00 (1024×1024)...
|
|
112
|
+
Quality 100 |██████████████████████████████| 100% Size: 476.46 KB
|
|
113
|
+
Trying scale factor 1.25 (1280×1280)...
|
|
114
|
+
Quality 100 |██████████████████████████████| 100% Size: 680.51 KB
|
|
115
|
+
Trying scale factor 1.50 (1536×1536)...
|
|
116
|
+
Quality 100 |██████████████████████████████| 100% Size: 903.38 KB
|
|
117
|
+
Trying scale factor 2.00 (2048×2048)...
|
|
118
|
+
Quality 96 |██████████████████████████████| 100% Size: 1011.68 KB
|
|
119
|
+
|
|
120
|
+
✓ Combined approach success: scale=2.00, size=1011.68 KB
|
|
107
121
|
Adjusting to exact target size...
|
|
108
|
-
|
|
109
|
-
Testing quality 96 |██████████████████████████████| 100%
|
|
110
|
-
|
|
111
|
-
✓ Quality adjusted to 96: 146.07 KB
|
|
112
|
-
Adding 103.93 KB padding...
|
|
113
|
-
✓ File padded to exact size
|
|
122
|
+
✓ Adjusted to exact size: 1.00 MB
|
|
114
123
|
|
|
115
124
|
╭─────────────┬────────────┬───────────────╮
|
|
116
125
|
│ Metric │ Original │ Processed │
|
|
117
126
|
├─────────────┼────────────┼───────────────┤
|
|
118
|
-
│ Dimensions │
|
|
127
|
+
│ Dimensions │ 1024×1024 │ 2048×2048 │
|
|
119
128
|
├─────────────┼────────────┼───────────────┤
|
|
120
|
-
│ Size │ 1.
|
|
129
|
+
│ Size │ 1.95 MB │ 1.00 MB │
|
|
121
130
|
├─────────────┼────────────┼───────────────┤
|
|
122
|
-
│ Target Size │ │
|
|
131
|
+
│ Target Size │ │ 1.00 MB │
|
|
123
132
|
├─────────────┼────────────┼───────────────┤
|
|
124
133
|
│ Difference │ │ 0 B (0.0%) │
|
|
125
134
|
├─────────────┼────────────┼───────────────┤
|
|
126
|
-
│ Reduction │ │
|
|
135
|
+
│ Reduction │ │ 48.8% smaller │
|
|
127
136
|
╰─────────────┴────────────┴───────────────╯
|
|
128
|
-
Time taken:
|
|
137
|
+
Time taken: 28.12 seconds
|
|
129
138
|
Output file: image_resized.webp
|
|
130
139
|
```
|
|
131
140
|
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
[](https://pypi.org/project/imgbytesizer/)
|
|
4
4
|
[](https://pepy.tech/projects/imgbytesizer)
|
|
5
|
+
[](https://codecov.io/gh/pyyupsk/imgbytesizer)
|
|
5
6
|
|
|
6
7
|
ImgByteSizer is a command-line tool that precisely resizes and optimizes images to match a specific file size while maintaining the best possible quality.
|
|
7
8
|
|
|
@@ -34,7 +35,7 @@ imgbytesizer image.jpg 500KB
|
|
|
34
35
|
imgbytesizer large_photo.jpg 500KB
|
|
35
36
|
|
|
36
37
|
# Resize and convert to WebP format
|
|
37
|
-
imgbytesizer image.png
|
|
38
|
+
imgbytesizer image.png 1MB -f webp
|
|
38
39
|
|
|
39
40
|
# Specify output file path
|
|
40
41
|
imgbytesizer photo.jpg 1MB -o compressed_photo.jpg
|
|
@@ -81,37 +82,45 @@ The tool prioritizes maintaining the highest possible quality while meeting the
|
|
|
81
82
|
## Example Output
|
|
82
83
|
|
|
83
84
|
```
|
|
85
|
+
❯ imgbytesizer image.png 1MB -f webp
|
|
86
|
+
|
|
84
87
|
◐ Opening image.png
|
|
85
88
|
File: image.png
|
|
86
89
|
Format: WEBP
|
|
87
|
-
Dimensions:
|
|
88
|
-
Size: 1.
|
|
89
|
-
Target size:
|
|
90
|
+
Dimensions: 1024 × 1024 pixels
|
|
91
|
+
Size: 1.95 MB
|
|
92
|
+
Target size: 1.00 MB
|
|
90
93
|
Trying quality adjustment without resizing...
|
|
91
|
-
Testing quality
|
|
92
|
-
✓ Found optimal quality:
|
|
94
|
+
Testing quality 100 |█████████████████░░░░░░░░░░░░░| 58% Size: 476.46 KB
|
|
95
|
+
✓ Found optimal quality: 100 (size: 476.46 KB)
|
|
96
|
+
Trying combined scaling and quality approach...
|
|
97
|
+
Trying scale factor 1.00 (1024×1024)...
|
|
98
|
+
Quality 100 |██████████████████████████████| 100% Size: 476.46 KB
|
|
99
|
+
Trying scale factor 1.25 (1280×1280)...
|
|
100
|
+
Quality 100 |██████████████████████████████| 100% Size: 680.51 KB
|
|
101
|
+
Trying scale factor 1.50 (1536×1536)...
|
|
102
|
+
Quality 100 |██████████████████████████████| 100% Size: 903.38 KB
|
|
103
|
+
Trying scale factor 2.00 (2048×2048)...
|
|
104
|
+
Quality 96 |██████████████████████████████| 100% Size: 1011.68 KB
|
|
105
|
+
|
|
106
|
+
✓ Combined approach success: scale=2.00, size=1011.68 KB
|
|
93
107
|
Adjusting to exact target size...
|
|
94
|
-
|
|
95
|
-
Testing quality 96 |██████████████████████████████| 100%
|
|
96
|
-
|
|
97
|
-
✓ Quality adjusted to 96: 146.07 KB
|
|
98
|
-
Adding 103.93 KB padding...
|
|
99
|
-
✓ File padded to exact size
|
|
108
|
+
✓ Adjusted to exact size: 1.00 MB
|
|
100
109
|
|
|
101
110
|
╭─────────────┬────────────┬───────────────╮
|
|
102
111
|
│ Metric │ Original │ Processed │
|
|
103
112
|
├─────────────┼────────────┼───────────────┤
|
|
104
|
-
│ Dimensions │
|
|
113
|
+
│ Dimensions │ 1024×1024 │ 2048×2048 │
|
|
105
114
|
├─────────────┼────────────┼───────────────┤
|
|
106
|
-
│ Size │ 1.
|
|
115
|
+
│ Size │ 1.95 MB │ 1.00 MB │
|
|
107
116
|
├─────────────┼────────────┼───────────────┤
|
|
108
|
-
│ Target Size │ │
|
|
117
|
+
│ Target Size │ │ 1.00 MB │
|
|
109
118
|
├─────────────┼────────────┼───────────────┤
|
|
110
119
|
│ Difference │ │ 0 B (0.0%) │
|
|
111
120
|
├─────────────┼────────────┼───────────────┤
|
|
112
|
-
│ Reduction │ │
|
|
121
|
+
│ Reduction │ │ 48.8% smaller │
|
|
113
122
|
╰─────────────┴────────────┴───────────────╯
|
|
114
|
-
Time taken:
|
|
123
|
+
Time taken: 28.12 seconds
|
|
115
124
|
Output file: image_resized.webp
|
|
116
125
|
```
|
|
117
126
|
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Terminal formatting utilities for imgbytesizer.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from typing import Optional
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def format_filesize(size_bytes: Optional[int], precision: int = 2) -> str:
|
|
9
|
+
"""Format file size in a human-readable format."""
|
|
10
|
+
if size_bytes is None:
|
|
11
|
+
return "N/A"
|
|
12
|
+
|
|
13
|
+
if size_bytes < 1024:
|
|
14
|
+
return f"{size_bytes} B"
|
|
15
|
+
elif size_bytes < 1024 * 1024:
|
|
16
|
+
return f"{size_bytes / 1024:.{precision}f} KB"
|
|
17
|
+
else:
|
|
18
|
+
return f"{size_bytes / (1024 * 1024):.{precision}f} MB"
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import sys
|
|
3
|
+
from typing import ClassVar, Dict, Optional, Tuple
|
|
4
|
+
|
|
5
|
+
from tabulate import tabulate
|
|
6
|
+
|
|
7
|
+
from .formatter import format_filesize
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
# ANSI Color Codes for beautiful terminal output
|
|
11
|
+
class Colors:
|
|
12
|
+
BLUE: ClassVar[str] = "\033[94m"
|
|
13
|
+
CYAN: ClassVar[str] = "\033[96m"
|
|
14
|
+
GREEN: ClassVar[str] = "\033[92m"
|
|
15
|
+
YELLOW: ClassVar[str] = "\033[93m"
|
|
16
|
+
RED: ClassVar[str] = "\033[91m"
|
|
17
|
+
ENDC: ClassVar[str] = "\033[0m"
|
|
18
|
+
BOLD: ClassVar[str] = "\033[1m"
|
|
19
|
+
UNDERLINE: ClassVar[str] = "\033[4m"
|
|
20
|
+
|
|
21
|
+
@staticmethod
|
|
22
|
+
def supports_color() -> bool:
|
|
23
|
+
"""Check if the terminal supports color output."""
|
|
24
|
+
# Add proper color support detection for different platforms
|
|
25
|
+
return sys.stdout.isatty()
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class ColoredFormatter(logging.Formatter):
|
|
29
|
+
"""Custom formatter for colored console output."""
|
|
30
|
+
|
|
31
|
+
FORMATS: ClassVar[Dict[int, str]] = {
|
|
32
|
+
logging.DEBUG: Colors.BLUE + "%(message)s" + Colors.ENDC,
|
|
33
|
+
logging.INFO: "%(message)s",
|
|
34
|
+
logging.WARNING: Colors.YELLOW + "%(message)s" + Colors.ENDC,
|
|
35
|
+
logging.ERROR: Colors.RED + Colors.BOLD + "%(message)s" + Colors.ENDC,
|
|
36
|
+
logging.CRITICAL: Colors.RED + Colors.BOLD + "%(message)s" + Colors.ENDC,
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
def format(self, record: logging.LogRecord) -> str:
|
|
40
|
+
log_fmt = self.FORMATS.get(record.levelno)
|
|
41
|
+
formatter = logging.Formatter(log_fmt)
|
|
42
|
+
return formatter.format(record)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def setup_logger() -> logging.Logger:
|
|
46
|
+
"""Setup and return the application logger."""
|
|
47
|
+
logger = logging.getLogger("imgbytesizer")
|
|
48
|
+
|
|
49
|
+
if not logger.handlers:
|
|
50
|
+
handler = logging.StreamHandler(sys.stdout)
|
|
51
|
+
|
|
52
|
+
if Colors.supports_color():
|
|
53
|
+
handler.setFormatter(ColoredFormatter())
|
|
54
|
+
else:
|
|
55
|
+
handler.setFormatter(logging.Formatter("%(message)s"))
|
|
56
|
+
|
|
57
|
+
logger.addHandler(handler)
|
|
58
|
+
logger.setLevel(logging.INFO)
|
|
59
|
+
|
|
60
|
+
return logger
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def print_progress_bar(
|
|
64
|
+
progress: int, total: int, prefix: str = "", suffix: str = "", length: int = 30
|
|
65
|
+
) -> None:
|
|
66
|
+
"""Print a progress bar with percentage."""
|
|
67
|
+
if not sys.stdout.isatty():
|
|
68
|
+
return # Don't print progress bars if not in a terminal
|
|
69
|
+
|
|
70
|
+
percent = min(100, int(100.0 * progress / total))
|
|
71
|
+
filled_length = int(length * progress // total)
|
|
72
|
+
bar = "█" * filled_length + "░" * (length - filled_length)
|
|
73
|
+
|
|
74
|
+
if Colors.supports_color():
|
|
75
|
+
print(
|
|
76
|
+
f"\r{prefix} |{Colors.GREEN}{bar}{Colors.ENDC}| {percent}% {suffix}",
|
|
77
|
+
end="\r",
|
|
78
|
+
)
|
|
79
|
+
else:
|
|
80
|
+
print(f"\r{prefix} |{bar}| {percent}% {suffix}", end="\r")
|
|
81
|
+
|
|
82
|
+
if progress == total:
|
|
83
|
+
print()
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def print_result(name: str, value: str, status: Optional[str] = None) -> None:
|
|
87
|
+
"""Print a name-value pair with optional status color."""
|
|
88
|
+
value_color = Colors.ENDC
|
|
89
|
+
if status == "good":
|
|
90
|
+
value_color = Colors.GREEN
|
|
91
|
+
elif status == "warning":
|
|
92
|
+
value_color = Colors.YELLOW
|
|
93
|
+
elif status == "bad":
|
|
94
|
+
value_color = Colors.RED
|
|
95
|
+
|
|
96
|
+
if Colors.supports_color():
|
|
97
|
+
print(f" {Colors.BOLD}{name}:{Colors.ENDC} {value_color}{value}{Colors.ENDC}")
|
|
98
|
+
else:
|
|
99
|
+
print(f" {name}: {value}")
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def print_processing_step(step: int, description: str) -> None:
|
|
103
|
+
"""Print a processing step with a spinner."""
|
|
104
|
+
if not sys.stdout.isatty():
|
|
105
|
+
logger = logging.getLogger("imgbytesizer")
|
|
106
|
+
logger.info(description)
|
|
107
|
+
return
|
|
108
|
+
|
|
109
|
+
spinner = ["◐", "◓", "◑", "◒"]
|
|
110
|
+
|
|
111
|
+
if Colors.supports_color():
|
|
112
|
+
print(f"{Colors.BLUE}{spinner[step % len(spinner)]}{Colors.ENDC} {description}")
|
|
113
|
+
else:
|
|
114
|
+
print(f"* {description}")
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def print_comparison_table(
|
|
118
|
+
original_size: int,
|
|
119
|
+
original_dimensions: Tuple[int, int],
|
|
120
|
+
final_size: int,
|
|
121
|
+
final_dimensions: Tuple[int, int],
|
|
122
|
+
target_size: int,
|
|
123
|
+
) -> None:
|
|
124
|
+
"""Print comparison table between original and processed image."""
|
|
125
|
+
if not sys.stdout.isatty():
|
|
126
|
+
# Use simpler output for non-terminal environments
|
|
127
|
+
logger = logging.getLogger("imgbytesizer")
|
|
128
|
+
logger.info(
|
|
129
|
+
f"Original: {original_dimensions[0]}×{original_dimensions[1]}, "
|
|
130
|
+
f"{format_filesize(original_size)}"
|
|
131
|
+
)
|
|
132
|
+
logger.info(
|
|
133
|
+
f"Processed: {final_dimensions[0]}×{final_dimensions[1]}, {format_filesize(final_size)}"
|
|
134
|
+
)
|
|
135
|
+
logger.info(f"Target: {format_filesize(target_size)}")
|
|
136
|
+
return
|
|
137
|
+
|
|
138
|
+
orig_dim = f"{original_dimensions[0]}×{original_dimensions[1]}"
|
|
139
|
+
new_dim = f"{final_dimensions[0]}×{final_dimensions[1]}"
|
|
140
|
+
orig_size = format_filesize(original_size)
|
|
141
|
+
new_size = format_filesize(final_size)
|
|
142
|
+
target = format_filesize(target_size)
|
|
143
|
+
diff = abs(final_size - target_size)
|
|
144
|
+
diff_pct = (diff / target_size) * 100
|
|
145
|
+
reduction = (
|
|
146
|
+
((original_size - final_size) / original_size) * 100 if original_size > final_size else 0
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
# Determine color based on how close to target
|
|
150
|
+
if diff_pct < 1:
|
|
151
|
+
diff_color = Colors.GREEN
|
|
152
|
+
elif diff_pct < 5:
|
|
153
|
+
diff_color = Colors.YELLOW
|
|
154
|
+
else:
|
|
155
|
+
diff_color = Colors.RED
|
|
156
|
+
|
|
157
|
+
if Colors.supports_color():
|
|
158
|
+
table = [
|
|
159
|
+
[
|
|
160
|
+
f"{Colors.BOLD}Dimensions{Colors.ENDC}",
|
|
161
|
+
f"{Colors.CYAN}{orig_dim}{Colors.ENDC}",
|
|
162
|
+
f"{Colors.GREEN}{new_dim}{Colors.ENDC}",
|
|
163
|
+
],
|
|
164
|
+
[
|
|
165
|
+
f"{Colors.BOLD}Size{Colors.ENDC}",
|
|
166
|
+
f"{Colors.CYAN}{orig_size}{Colors.ENDC}",
|
|
167
|
+
f"{Colors.GREEN}{new_size}{Colors.ENDC}",
|
|
168
|
+
],
|
|
169
|
+
[
|
|
170
|
+
f"{Colors.BOLD}Target Size{Colors.ENDC}",
|
|
171
|
+
"",
|
|
172
|
+
f"{Colors.BLUE}{target}{Colors.ENDC}",
|
|
173
|
+
],
|
|
174
|
+
[
|
|
175
|
+
f"{Colors.BOLD}Difference{Colors.ENDC}",
|
|
176
|
+
"",
|
|
177
|
+
f"{diff_color}{format_filesize(diff)} ({diff_pct:.1f}%){Colors.ENDC}",
|
|
178
|
+
],
|
|
179
|
+
[
|
|
180
|
+
f"{Colors.BOLD}Reduction{Colors.ENDC}",
|
|
181
|
+
"",
|
|
182
|
+
(
|
|
183
|
+
f"{Colors.CYAN}{reduction:.1f}% smaller{Colors.ENDC}"
|
|
184
|
+
if reduction else f"{Colors.YELLOW}N/A{Colors.ENDC}"
|
|
185
|
+
),
|
|
186
|
+
],
|
|
187
|
+
]
|
|
188
|
+
|
|
189
|
+
headers = [
|
|
190
|
+
f"{Colors.UNDERLINE}Metric{Colors.ENDC}",
|
|
191
|
+
f"{Colors.UNDERLINE}Original{Colors.ENDC}",
|
|
192
|
+
f"{Colors.UNDERLINE}Processed{Colors.ENDC}",
|
|
193
|
+
]
|
|
194
|
+
else:
|
|
195
|
+
table = [
|
|
196
|
+
["Dimensions", orig_dim, new_dim],
|
|
197
|
+
["Size", orig_size, new_size],
|
|
198
|
+
["Target Size", "", target],
|
|
199
|
+
["Difference", "", f"{format_filesize(diff)} ({diff_pct:.1f}%)"],
|
|
200
|
+
["Reduction", "", f"{reduction:.1f}% smaller" if reduction else "N/A"],
|
|
201
|
+
]
|
|
202
|
+
|
|
203
|
+
headers = ["Metric", "Original", "Processed"]
|
|
204
|
+
|
|
205
|
+
print()
|
|
206
|
+
print(tabulate(table, headers=headers, tablefmt="rounded_grid"))
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Command-line interface for imgbytesizer.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import logging
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from .logger import setup_logger
|
|
11
|
+
from .resizer import resize_to_target_filesize
|
|
12
|
+
from .utils import IMG_FORMATS, parse_filesize
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def main() -> int:
|
|
16
|
+
"""Main entry point for the CLI."""
|
|
17
|
+
# Setup logger
|
|
18
|
+
logger = setup_logger()
|
|
19
|
+
|
|
20
|
+
parser = argparse.ArgumentParser(
|
|
21
|
+
description="Resize an image to match a target file size",
|
|
22
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
23
|
+
epilog="""
|
|
24
|
+
Examples:
|
|
25
|
+
%(prog)s image.jpg 500KB # Resize to 500 KB
|
|
26
|
+
%(prog)s photo.png 2MB -o small_photo.png # Resize to 2 MB with custom output
|
|
27
|
+
%(prog)s image.jpg 100KB -f webp # Resize and convert to WebP
|
|
28
|
+
%(prog)s large.jpg 50KB --min-dimension 200 # Ensure min dimension is 200px
|
|
29
|
+
%(prog)s -v # Show version information
|
|
30
|
+
""",
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
parser.add_argument("image_path", nargs="?", help="Path to the input image")
|
|
34
|
+
parser.add_argument("target_size", nargs="?", help='Target file size (e.g., "1MB", "500KB")')
|
|
35
|
+
parser.add_argument("-o", "--output", help="Output path (default: input_resized.ext)")
|
|
36
|
+
parser.add_argument("-f", "--format", choices=IMG_FORMATS, help="Output format")
|
|
37
|
+
parser.add_argument("--min-dimension", type=int, help="Minimum width/height in pixels")
|
|
38
|
+
parser.add_argument(
|
|
39
|
+
"--no-exact",
|
|
40
|
+
action="store_true",
|
|
41
|
+
help="Do not pad file to get exact target size",
|
|
42
|
+
)
|
|
43
|
+
parser.add_argument("-v", "--version", action="store_true", help="Show version information")
|
|
44
|
+
parser.add_argument("--debug", action="store_true", help="Enable debug logging")
|
|
45
|
+
parser.add_argument("-q", "--quiet", action="store_true", help="Minimal output")
|
|
46
|
+
|
|
47
|
+
# Handle version flag before checking required arguments
|
|
48
|
+
args = parser.parse_args()
|
|
49
|
+
|
|
50
|
+
# Handle version request
|
|
51
|
+
if args.version:
|
|
52
|
+
from . import __version__
|
|
53
|
+
|
|
54
|
+
print(f"imgbytesizer v{__version__}")
|
|
55
|
+
return 0
|
|
56
|
+
|
|
57
|
+
# Set logging level
|
|
58
|
+
if args.debug:
|
|
59
|
+
logger.setLevel(logging.DEBUG)
|
|
60
|
+
elif args.quiet:
|
|
61
|
+
logger.setLevel(logging.WARNING)
|
|
62
|
+
|
|
63
|
+
# Handle no arguments case with nice help
|
|
64
|
+
if args.image_path is None or args.target_size is None:
|
|
65
|
+
parser.print_help()
|
|
66
|
+
return 0
|
|
67
|
+
|
|
68
|
+
# Validate input file exists
|
|
69
|
+
image_path = Path(args.image_path)
|
|
70
|
+
if not image_path.exists():
|
|
71
|
+
logger.error(f"Input file not found: {args.image_path}")
|
|
72
|
+
return 1
|
|
73
|
+
|
|
74
|
+
try:
|
|
75
|
+
target_bytes = parse_filesize(args.target_size)
|
|
76
|
+
except ValueError as e:
|
|
77
|
+
logger.error(f"Error: {e}")
|
|
78
|
+
return 1
|
|
79
|
+
|
|
80
|
+
try:
|
|
81
|
+
output_path = resize_to_target_filesize(
|
|
82
|
+
args.image_path,
|
|
83
|
+
target_bytes,
|
|
84
|
+
args.output,
|
|
85
|
+
args.format,
|
|
86
|
+
args.min_dimension,
|
|
87
|
+
exact_size=not args.no_exact,
|
|
88
|
+
quiet=args.quiet,
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
logger.debug(f"Successfully processed image: {output_path}")
|
|
92
|
+
return 0
|
|
93
|
+
except KeyboardInterrupt:
|
|
94
|
+
logger.warning("Process interrupted by user.")
|
|
95
|
+
return 130
|
|
96
|
+
except Exception as e:
|
|
97
|
+
logger.error(f"Error: {str(e)}")
|
|
98
|
+
if args.debug:
|
|
99
|
+
logger.exception("Detailed error information:")
|
|
100
|
+
return 1
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
if __name__ == "__main__":
|
|
104
|
+
sys.exit(main())
|