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